XmlSerializer does not encode special characters like &

I have a class named Config that I would like to serialize to XML using 
XmlSerializer. That class has a couple of string properties that may contain 
special characters like <, >, &, etc. I am currently using the following 
method to serialize the instance (m_Config) of the class:

Private Sub SerializeConfiguration()
    Dim userStorage As IsolatedStorageFile = 
IsolatedStorageFile.GetUserStoreForAssembly
    Dim fileStream As IsolatedStorageFileStream = New 
IsolatedStorageFileStream("Config.XML", IO.FileMode.Create, userStorage)
    Dim serializer As XmlSerializer = New XmlSerializer(GetType(Config))
    serializer.Serialize(fileStream, m_Config)
    fileStream.Close()
End Sub

The problem with this method is that special characters (e.g. <, >, &) are 
not encode (e.g. to <, >, &), so the output is not well-formed XML.

Is there an easy and proper way to make XmlSerializer encode special 
characters. I do not want to encode the data inside the instance of my Config 
class.

Thanks and kind regards
Sebastian
0
10/15/2009 3:31:32 PM
dotnet.xml 7266 articles. 0 followers. Follow

3 Replies
1171 Views

Similar Articles

[PageSpeed] 26

Sebastian Daser schrieb:

> The problem with this method is that special characters (e.g. <, >, &) are 
> not encode (e.g. to <, >, &), so the output is not well-formed XML.

'<' and '>' are enclosing characters of the tags. Having these in the
content might mix up tag hierarchy.

Quote from http://en.wikipedia.org/wiki/Xml#Characters_and_escaping
| The characters "<" and "&" are key syntax markers and may never appear in content

> Is there an easy and proper way to make XmlSerializer encode special 
> characters. 

I guess not. I have seen the same behaviour.

CU,
Christian
0
10/15/2009 5:13:46 PM
Sebastian Daser wrote:
> I have a class named Config that I would like to serialize to XML using 
> XmlSerializer. That class has a couple of string properties that may contain 
> special characters like <, >, &, etc. I am currently using the following 
> method to serialize the instance (m_Config) of the class:
> 
> Private Sub SerializeConfiguration()
>     Dim userStorage As IsolatedStorageFile = 
> IsolatedStorageFile.GetUserStoreForAssembly
>     Dim fileStream As IsolatedStorageFileStream = New 
> IsolatedStorageFileStream("Config.XML", IO.FileMode.Create, userStorage)
>     Dim serializer As XmlSerializer = New XmlSerializer(GetType(Config))
>     serializer.Serialize(fileStream, m_Config)
>     fileStream.Close()
> End Sub
> 
> The problem with this method is that special characters (e.g. <, >, &) are 
> not encode (e.g. to <, >, &), so the output is not well-formed XML.

Are you posting using the web interface to the newsgroups?
Unfortunately discussing encoding questions that way is difficult as any 
entity references you might have used are not showing up.

> Is there an easy and proper way to make XmlSerializer encode special 
> characters. I do not want to encode the data inside the instance of my Config 
> class.


I don't see that problem.
With e.g.

     class Program
     {
         static void Main(string[] args)
         {
             Foo foo1 = new Foo() { Bar = "a < b && b < c" };
             XmlSerializer ser = new XmlSerializer(typeof(Foo));
             ser.Serialize(Console.Out, foo1);
             Console.WriteLine();
         }
     }

     public class Foo
     {
         public string Bar { get; set; }
     }

the characters '<' and '&' are properly escaped
(as '& l t;' and '& a m p;', only without the spaces I inserted in the 
hope the web interface shows what I want).

-- 

	Martin Honnen --- MVP XML
	http://msmvps.com/blogs/martin_honnen/
0
mahotrash (1778)
10/15/2009 5:37:58 PM
I have found out now.... I need to use XmlTextWriter.

My code now looks like:

Private Sub SerializeConfiguration()
    Dim userStorage As IsolatedStorageFile = 
IsolatedStorageFile.GetUserStoreForAssembly
    Dim fileStream As IsolatedStorageFileStream = New 
IsolatedStorageFileStream("Config.XML", IO.FileMode.Create, userStorage)
    Dim xmlTextWriter as new XmlTextWriter(fileStream, Text.Encoding.Unicode)
    Dim serializer As XmlSerializer = New XmlSerializer(GetType(Config))
    serializer.Serialize(xmlTextWriter, m_Config)
    fileStream.Close()
End Sub


"Sebastian Daser" wrote:

> I have a class named Config that I would like to serialize to XML using 
> XmlSerializer. That class has a couple of string properties that may contain 
> special characters like <, >, &, etc. I am currently using the following 
> method to serialize the instance (m_Config) of the class:
> 
> Private Sub SerializeConfiguration()
>     Dim userStorage As IsolatedStorageFile = 
> IsolatedStorageFile.GetUserStoreForAssembly
>     Dim fileStream As IsolatedStorageFileStream = New 
> IsolatedStorageFileStream("Config.XML", IO.FileMode.Create, userStorage)
>     Dim serializer As XmlSerializer = New XmlSerializer(GetType(Config))
>     serializer.Serialize(fileStream, m_Config)
>     fileStream.Close()
> End Sub
> 
> The problem with this method is that special characters (e.g. <, >, &) are 
> not encode (e.g. to <, >, &), so the output is not well-formed XML.
> 
> Is there an easy and proper way to make XmlSerializer encode special 
> characters. I do not want to encode the data inside the instance of my Config 
> class.
> 
> Thanks and kind regards
> Sebastian
0
10/19/2009 6:30:06 PM
Reply:

Similar Artilces:

how to draw picture like this?
http://progame.6600.org/bbs/images/upload/2003/08/08/132409.gif can visio do this job? or other software? That looks like a simple enough drawing for Visio - you will need simply play with the tool and select the correct Stencils for the figures. Check out some samples here: http://www.microsoft.com/office/visio/evaluation/indepth/samples.asp >>This posting is provided "AS IS" with no warranties, and confers no rights.<< >>Please note I cannot respond to e-mailed questions. << >>Please use these newsgroups. << "progame" <progam...

paste special
i just got a new computer and it runs office 2003. and now i can't get my paste special to work, and i don't know why. I make a powerpoint slide then i copy the slide and select past special in publisher. i choose the file type to be enhanced metafile. and it copies just fine. but when i edit the powerpoint slide it won't update on my publisher slide like it used to do. do i need to paste it as a file type other than enhanced metafile? You cannot paste something as an enhanced metafile and then expect it to update with PowerPoint. You need to paste the PowerPoint slide as...

XmlSerializer Collection with Collections
Hello I got this working but it is not how I really want it, basically I have an xml file which has a root of <test> and can be filled with 3 different types of <question> elements with different attributes, all share a base set of 4, one of the question types can have children with <option> elements, this is how the xml looks after serialization.... If you notice there is an extra <SelectionList> around the <option>'s in the final <question>, how can I write my class so I don't have this extra <SelectionList> element....my class follows, you ...

Encoding problem #3
I'm trying to do a transform (Using XmlTransform class in c#) and in the Transform I'm specifying the the output xsl below: <xsl:output method="xml" encoding="UTF-8" indent="no"/> the resulting xml ends up with the following declaration: <?xml version="1.0" encoding="utf-16"?> changing the encoding to utf-16, is there something I'm doing wrong? Is it possible to make the resulting xml declaration omit the encoding all together? thanks Demon News wrote: > I'm trying to do a transform (Using XmlTransfo...

Special Form
Hi All, I need to create a subform that contains a list of items, where the items are always in view like on a spreadsheet. Using the Items as column 1 I need another column for data entry and the other columns are for historical data. When I create a query for the Subform to show the blank list & the historical of course I cant input anything because of the historical data, but if the subform is just based on the item want, it works. How do I get all the information in 1 subform without loosing the item list from (historical query) . Any suggestions would be wonderful Ok I...

locking toolbars like IE....
All, How can I implement locking toolbars like Internet Explorer? I can't seem to find any info on doing that. Thanks, Craig Klementowski Craig, you may check out this tutorial http://www.codeproject.com/atl/ietoolbartutorial.asp TECH http://www.tversoft.com "Craig Klementowski" <nospam.craigklem@nospam.hotmail.com> wrote in message news:e1irXKX9DHA.3704@tk2msftngp13.phx.gbl... > All, > > How can I implement locking toolbars like Internet Explorer? I can't seem to > find any info on doing that. > > Thanks, > > > Craig Klementowski >...

XmlSerializer
I'm having a basic problem with the XmlSerializer & i'm at my wits end trying to sort it out i have a basic clas <Serializable()> Class Tes Public Name as Strin End Clas when this serializes i wan <Test><Name>Value</Name></Test the problem is if i use the XmlSerializer clas Dim t as Tes t.Name="Value Dim sb As New StringBuilde Dim sw As New StringWriter(sb Dim Serializer As New XmlSerializer(Message.GetType Serializer.Serialize(sw, t Serializer = Nothin Console.Write(sb.ToStr...

Create hotmail like http based mail for outlook ?
Hi, Is it possible to create a hotmail like http based email in Exchange, (I don't mean OWA cos it's pure web based ONLY) ? I'm looking for a solution for travelling outlook clients so they can download mail via outlook (via http port) and work offline. And I'm looking for an alternative sol'n besides POP3 cos many sites would not allow POP3/SMTP access at client side. Any help appreciated. TIA, Alex You should try one of the Exchange newsgroups - they'll be better able to tell you how to set up Exchange to do this. Note that the HTTP account support f...

Outlook 2003, can it look like OXP?
Is there a way to get Outlook 2003 to look like Outlook XP (folder list on the left, inbox above, preview pane below)? I can't be in the minority that doesn't like the new layout. Thanks. symfnyx wrote: > Is there a way to get Outlook 2003 to look like Outlook XP (folder > list on the left, inbox above, preview pane below)? I can't be in > the minority that doesn't like the new layout. Thanks. One of the what's new, ahem, "features" that counted as a negative for me (and another reason that I haven't upgraded; no bang for the buck). Oooh, boy,...

To write living will do I need special format
I just need to change and update a living trust You should consult someone with the appropriate legal knowledge in the jurisdiction in which you are domiciled. -- Hope this helps. Please reply to the newsgroup unless you wish to avail yourself of my services on a paid consulting basis. Doug Robbins - Word MVP, originally posted via msnews.microsoft.com "belladonna" <belladonna@discussions.microsoft.com> wrote in message news:F25A64CB-355F-44E9-A005-16AA61DA15A7@microsoft.com... > I just need to change and update a living trust ...

XmlSerializer and shared objects (or How to generate IDREFs using XmlSerializer)
This is a multi-part message in MIME format. ------=_NextPart_000_007F_01C34AC1.11D4FB20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I am trying to find a solution that will allow me to use XmlSerializer = to serialize/deserialize a collection of objects where a given object is = shared between two or more other objects, and not create duplicate XML = representations of the shared object, but instead use IDREFs to refer to = the shared object. The XML I'm trying to produce is as follows (where "href" is an IDREF): <...

List of users with special criteria
Hello All, I'm trying to generate a report with the following data: - Any user with a mailbox - Each user that has restricted external IN/OUT capabilities The following processes are being used to restrict sending/receiving internet email: Block Send: http://www.msexchange.org/tutorials/MF009.html Block Receive: http://www.msexchange.org/tutorials/MF025.html I've been searching for about 2 hours and have come up with zilch. Any help is much appreciated. Thanks, Ken In the first case - to list all users blocked from sending outbound mail, you need to find the groups/user...

Word document sent by Mac client lost encoding when opened in OWA
When a Macintosh users sends a Word or Excel document(with the proper Windows extentions) the Word document loses its encoding when you try to open it with the OWA. The Excel document is unrecognized. When you open the message with an Outlook client on Windows or Mac the attachments are fine. ...

Problems with german characters (umlaute)
Hello colleagues, it happes every months that a mail reaches us with I don't know how coded german characters. Our german customers are calling us, asking what we're missing on our system. I've checked one of these mails and the only thing I found out that the codepage, which was specified in the header, was the same than in the other mails I've in my mailbox and which I can read perfectly. The strange thing in current case is, that the email is displayed correctly when the mail is opened in Outlook Web Access. I need some help how to get hand on these problems. Many...

Specify certain length(characters) when defining a column
Is there anyway to specify a certain character length when defining a column in excel? The worksheet in excel has to be exported into notepad. The notepad data has to have a predetermined amount of characters in each column. ...

XmlSerializer and inherited objects
Hi I have a hirachy of classes which are Message(base), then FileMessage and ChatMessage (extended) I want to serialize the objects and when i am deserizaling i dont know if i am getting FileMessage or ChatMessage. So how to get that object and use it I have written following code for serialization public void Send(Message message) { NetworkStream netWorkStream=null; try { XmlSerializer serializer=new XmlSerializer(message.GetType()); netWorkStream=new NetworkStream(_clientSocket); Stream stream=(Stream)netWorkStream; serializer.Serialize(stream,message); } finally { netWorkStrea...

Loading CSV and Special character
Hi, i was wandering if i was able to put an ascii character in a CSV file to be able to force a page-break in Excel when i load the file. Been trying Ascii character 11 and 10. But none are working! Is that doable? Or should i output a formula/Excel command (which i dont know) to do it? Thanks guys! ...

XMLSerializer Serialize
Iam trying to create a xml file by serializing a custom business object. Iam using a xmltextwriter, but the problem there are invalid characters at the end of the generated file anyone knows a way around it ? tia Dim myStream As New IO.MemoryStream Dim myXMLWriter As New System.Xml.XmlTextWriter(myStream, System.Text.Encoding.UTF8) myXMLWriter.Formatting = System.Xml.Formatting.Indented Dim myShipments As OrderShipments myShipments = CType(myOrder.OrderAddresses(0), COrderAddress).Shipments myShipments.ToXML(myXMLWriter) ...

Allow searching of date fields to allow wildcard characters
For fields such as birthdays and expiry dates, customers often want to search the database for a list of contacts with birthdays. It would be great if you would allow wildcards in date field searches so that we could search for all birthdays that occur in a specific month. The year is not always relevant when performing date searches. Birthdays is a common search performed by customers in the financial sector as well as other industries. Currently, we have to add an additional text field to facilitate this type of search. It adds confusion to the users, in some cases double data entry...

Special Characters not resolving
When I load XML from a file into a dotNet XMLDataDocument, the UTF-8 codes are resolved but the 5 special XML entities are not. How can I force those 5 special character types to be translated? Trac Bannon wrote: > When I load XML from a file into a dotNet XMLDataDocument, the UTF-8 codes > are resolved but the 5 special XML entities are not. > > How can I force those 5 special character types to be translated? Please show us an XML sample you have and then explain us which properties or methods of XmlDataDocument exactly you use. For instance with e.g. <eleme...

Like data
I need to match (or find like kind) in different columns. I also need associated data (in other columns) to follow the columns when they are matched. In the example Column A has associated data in column B. Column C has associated data in column D. How do I match data in columns A and C and ensure data integrity in columns B and D. Example Column A B C D A B C 1 a 3 x 1 a 1 3 x 7 z 3 x 3 7 z 0 l 7 z 7 9 k...

OWA URLSCAN causing 404 errors not allowing special chars
Anyone know how to set urlscan to allow "&" and "%" in the subject line when OWA server is configured as a front-end server? Am trying to follow KB320089 and KB309508 with no luck and have restarted both IIS Admin services and WWW services on both front end server and back end server. Also tried removing instead of commenting... Anyone else had this problem and fix for? Thanks in advance, Jim ...

Special Folder Location
CSIDL_COMMON_APPDATA.........Is this a valid folder for Win2K thru Win7? (How can I be sure the program works thru Vista & 7 when we don't have a PC w/Vista or 7 on it ?!?!.....(Rhetorical)) TIA, DanS DanS <t.h.i.s.n.t.h.a.t@r.o.a.d.r.u.n.n.e.r.c.o.m> wrote: >CSIDL_COMMON_APPDATA.........Is this a valid folder for Win2K thru Win7? > >(How can I be sure the program works thru Vista & 7 when we don't have a PC >w/Vista or 7 on it ?!?!.....(Rhetorical)) If you are a developer then you should be testing your software using Virtual PC, VMW...

Web Special - ELLIOT WAVE PRINCIPLE
GET the 10th Edition of ELLIOT WAVE PRINCIPLE by Frost and Prechter for 40% off. The Definitive Resource on Elliot Wave Theory and Application.... This hardcover book covers fundamentals, use, and market forecasting. At 248 pages, this book provides detailed information on Wave formation, Mathematical Patterns, Wave Approaches, and Ratio Theory. By reknown Elliot experts Robert Prechter and Alfred John Frost - there is no better resource in understanding, applying, and profiting from Elliot Wave Theory. LIST PRICE OF $49.50 - HARDCOVER, 248pgs. WEB SPECIAL : $29.50 ( FREE SHIPPING IN US ) ...

Google-like searching of my Exchange mailbox?
Hello All, As a follow up to my earlier post, can anyone recommend any software that would allow me to perform a google-like (i.e. pre-indexed, full text search) on my Exchange 2k3 mailbox? In the perfect world, this would also somehow integrate with OWA so I could do it from anywhere. (I've been using GMail, and I want to do that functionality on my own E2k3 server.) Thanks, Brian ...