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
2370 Views

Similar Articles

[PageSpeed] 49

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 (1777)
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:

UTF8 Encoding
I have a problem where I am working with extended character sets in XML but I have also found that any time I work with a translation or internally generated Xml document I get the dreaded message, "Data at the root level is invalid. Line 1 position 1". If you run the following code there will be extra bytes at the beginning of the resulting string. I believe this is some type of BigEndian encoding or something. My question is this, how do I do this and load the result into the DOM object and keep all character encoding in tact? Thanks, Matt using System; using System.Xml...

MSN-Like Chat window
Hi, Im trying to put an msn-like chat window on my program. I want to be able to select text in the window, and it needs a vertical scrollbar. I also want to be able to put images in the text (smileys). How can i do this? And also, how can i put the window on top of its parent window without flickering? Any help would be appreciated :) and if you cant help me, thx for reading anyway :) Thomas ...

chart in excel like google finance chart
I've been playing around with google finance and am wondering if a chart like that can be implemented in excel. Some of the features I'm very interested in is the ability to be able to select a time window and chart the trend. I need to create a chart that is basically identical to the google and yahoo finance charts. Is this possible at all in excel or is this an impossible task and I should look elsewhere. If impossible what are some suggestions for accomplishing this? Thanks, Can you post back with the chart you have in mind? More than likely you can create the chart in Exc...

I would like to increase my budget figures by a percentage
It is buget time and we need to increase the 2004 figures by 2% for 2005 is there a formula that can do this in one command enter 102% in a separate cell Copy that cell Select all the cells to increase Goto Edit>PasteSpecial and select the Multiply button in the Operation section OK out -- HTH RP (remove nothere from the email address if mailing direct) "Wendy" <Wendy@discussions.microsoft.com> wrote in message news:35FA2EA4-4144-4966-B7BC-3E314C0FEECC@microsoft.com... > It is buget time and we need to increase the 2004 figures by 2% for 2005 is > there a formu...

I would like to add a base line to a chart ...
I have a chart which tracks workhours per week. Across the bottom are the dates representing the ends of the weeks (1/7/07 through 12/30/07), and along the left are possible hours per week (0 through 70). I am using a line chart with markers. I would like to add a base line or indicator line across the chart at 45 hours. How can I add a base line at 45 hours. (I don't have the base line data in my spreadsheet.) Thank you for your help. Darrell Add a line to a line or column chart: http://peltiertech.com/Excel/Charts/AddLine.html - Jon ------- Jon Peltier, Microsoft Excel MVP Tu...

255 Character Truncation, Vlookup Macro vs. Opening Workbook Macro
Hello, I just posted an entry on the microsoft.public.excel.programming forum, but thought I'd post it here as well. http://groups-beta.google.com/group/microsoft.public.excel.programming/browse_thread/thread/40fae474a64d6900/ce8e97e11e429402#ce8e97e11e429402 I forgot to complete the subject line on that post. Any ideas? But you already have a response in .programming. It's pretty unusual that you'd have to post to multiple forums. But if you think you must, try to post to both at one time. jrew23@yahoo.com wrote: > > Hello, > > I just posted an entry on the mi...

Preserving character attributes in a RichTextBox
Hello, I am using a RichTextBox to display many lines of text, where the characters are of various colors. To keep the text box from getting fuller than I would like, each time it reaches a specific number of lines I copy its contents out to a string array, copy only the last "n" lines of that array into another string array, then reassign that new smaller array into the text box. As a result the text box then only displays the newer lines. For example: int linesInBox = richTextBox0.Lines.Length; if (linesInBox > MAX_LINES_WANTED_IN_BOX) { // Get all lin...

Choosing the square character as a delimiter
Just wondering if anyone knows how to choose the square character as a delimiter when importing a text file into Excel. I can't copy or paste it. Thanks in advance. Depends on what that is. If it's alt-enter, you can hit and hold the alt key while typing 0010 on the numeric keypad (or even just hit ctrl-j). You can use Chip Pearson's Cell View addin to find out the character it is: http://www.cpearson.com/excel/CellView.htm Once you know what it is, you could try the alt-#### to see if it works. If it doesn't, you could use a macro to change it to a different charact...

Determine last character typed
Is there a way to determine the last character typed in a text box? I want to run code in the on change event of a text box but not if the last letter typed is a space. TIA, Tim Read the Text property of the textbox (note: Text is a property that can be read only when the textbox has the focus) and test the last character in the Text property's result: Private Sub TextBoxName_Change() If Right(Me.TextBoxName.Text, 1) <> " " Then ' your code goes here End If End Sub -- Ken Snell <MS ACCESS MVP> "Tim J La Fazia" <timj.lafazia@idc-...

In Excel Remove what looks like a key with + on it. Anchored on pa
On my EXCEL SCREEN I have what looks like Keyboard keys with + or +- on them. How do delete them? What are they? Try: * 'Data' >'Subtotals...' > 'Remove All'. OR: * 'Data' > 'Group & Outline' > 'Ungroup'. Micky "Ed Walsh" wrote: > On my EXCEL SCREEN I have what looks like Keyboard keys with + or +- on them. > How do delete them? What are they? ...

How do I get entries over 1000 characters to display in a cell?
I'm converting a paper form to an excel version. I need one cell for the user to enter a narrative. I want the printed copy to show the full entry. I think 2000 to 2500 characters is probably long enough for most users. The problem I'm running into is text that stops wrapping after about a 1000 characters. Thanks for any help. Whilst there is the method of inserting ctrl/enter characters to reflec more text you will find the odd user who will demand that 'more characters are displayed. This, of course, also applies to printing. One method is to insert 31 following r...

Can I use a header or footer more than 255 characters in Excel?
What can I do if I need to insert more than 255 characters in a header or footer in Excel 2003? And can I make some grid lines for a header or footer in Excel 2003? Thank you for your help! The combined length of all third headers or footers (left, center and right) may not exceed 255 and you cannot change it. The only 'workaround' I can think of is to create them right in the worksheet itself. -- Jim "Jin Qingfeng" <Jin Qingfeng@discussions.microsoft.com> wrote in message news:C4DF2013-2443-486E-9386-9C8862B96DB3@microsoft.com... | What can I do if I need to i...

How do I display unicode characters in a web page using an isapi dll?
I have an ISAPI extension DLL that needs to output unicode data using the WriteClient() function. The unicode characters are not displayed properly. The text that is displayed in the web browser looks like garbage even though viewing the source HTML shows Chinese characters correctly. DWORD WINAPI HttpExtensionProc(EXTENSION_CONTROL_BLOCK *pECB) { DWORD dwLength; std::wstring html; html =3D L"<html><head><meta http-equiv=3D'content-type' content=3D'text/html; charset=3Dutf-8' /></head><body><p>=C6=...

Using a IF formula, I would like to drop the 2 digits in front of.
Using a IF formula, I would like to drop the 2 digits in front of the decimal, and only use the 2 digits after the decimal =MOD(A1,1) will return decimal -- Regards, Peo Sjoblom (No private emails please, for everyone's benefit keep the discussion in the newsgroup/forum) "osuhoosier" <osuhoosier@discussions.microsoft.com> wrote in message news:3899ADB5-3AAB-482C-AF4C-9A71DEF3D28C@microsoft.com... > Using a IF formula, I would like to drop the 2 digits in front of the > decimal, and only use the 2 digits after the decimal Not sure I get this but the form...

How many characters per cell
How many characters can you fit into one cell. We are having a problem with text being cut off when printing, but i shows up when viewing on either Print Preview or normal view -- aletoconstc ----------------------------------------------------------------------- aletoconstco's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=3533 View this thread: http://www.excelforum.com/showthread.php?threadid=55334 Excel Help on "limits" or "specifications" reveals that Excel will allow 32,767 characters to be entered in a cell. However, it goes on t...

Character Query
I have a file that I need to query that has names of cities in a particular field. I need to find all cities that have more than 4 characters in its name. Thanks in advance. "KIMA06" <KIMA06@discussions.microsoft.com> wrote in message news:D6E71192-759C-4F90-9265-816E60CE4F64@microsoft.com... >I have a file that I need to query that has names of cities in a particular > field. I need to find all cities that have more than 4 characters in its > name. Thanks in advance. WHERE Len([NameOfField]) > 4 If the value may be null, you might need to modify that to som...

Trim characters
Hello there Which are those characters that CString removes when you call CString::Trim function of it? One of them is \0, I want others or entire list. As well as what is similar function to trim those characters for LPSTR or LPWSTR ? >Hello there >Which are those characters that CString removes when you call >CString::Trim function of it? The documentation says: "Removes all leading and trailing occurrences of one of the following: The character specified by chTarget. All characters found in the string specified by pszTargets. Whitespace. " >One of them is \0 I...

Looks like a bug with copy\paste from cmd to word.
WinXP 5.1.2600 SP3 Build 2600, and word 2007 v12.0 bulid 6514 When I paste from CMD to Word, space between letters and "%" symbol disappears; for example every time I copy from cmd something like "md %xxx%' and paste it into word, I get "md%xxx%" Is it a bug? or it is a kind of feature? Thanks "Dmitry" <Dmitry@discussions.microsoft.com> wrote in message news:B1025A22-6BFF-486A-B92B-8FCBC7BB1E81@microsoft.com... > WinXP 5.1.2600 SP3 Build 2600, and word 2007 v12.0 bulid 6514 > When I paste from CMD to Word, space between letter...

set up a worksheet in excel like a check register with auto sum
I would like to set up a worksheet in Excel for my check registor that will automatically give me the balance. jthhousing, have a look here and see if this will do what you want, http://office.microsoft.com/en-us/templates/TC010186511033.aspx If not I have one set up, if you would like to have a look at it let me know and I will send you a copy -- Paul B Always backup your data before trying something new Please post any response to the newsgroups so others can benefit from it Feedback on answers is always appreciated! Using Excel 2002 & 2003 "jthhousing" <jthhousing@d...

Tab Key acting like Alt-Tab
Lately, when I've been trying to use the tab key, I get that Windows switch thing that supposed to happen when you alt-tab. I don't know whether I'm doing something to make that happen or need to re-map my keyboard. It usually starts after I'm using FaceBook weirdly enough. Any ideas? Could be option enabled in "Ease of Access" (used to be called by a more sensible name "Accessibility"). So check those options, e.g. 'sticky keys" options, etc. If that doesn't solve issue, are you sure "Alt" is not faulty i.e. not stuck...

Specialized Spreadsheet
Anybody want to tackle a special request for a specialized spreadsheet function? I need a way to track persons progress on a project. for example, they have 2080 hours in a work year. I need to account for holidays and weekends then if they are what ever project they can charge to. For example if they have 500 hrs on one project, 300 on another etc, planned days off and vacation it should project their time etc. My office e-mail is mgomien@shearerassociates.us -- Michael Gomien Do you use MS Project. You can write macros in MS project that wil export the data into...

Special Rights needed for ODBC access in WIN 7-64?
I have an access 2007 database, frontending a MYSQL database. Works fine on all of our XP boxes. For WIn7: When I go into ODBC administration, I can set up the ODBC connection, as a System data source, and it tests fine. When I actually try to use the database, I get Connection failed, even just trying to open the ODBC linked tables. If I try to create a new link, it is really weird. I get a dialog box with two tabs: File Data Source and Machine Data Source. SYSTEM data source, which is the way my source is configured is not even an option. When I hit NEW connection...

15 character field truncating
This isn't really a question. I just need to explain properly from a more authoritative voice than myself why something is happening to a client. She is entering a 15 digit character in excel (all numbers). It is truncating it down to a few numbers plus that e+ thing. For example entering 153469874563216 becomes 1.5437E+14 when the cell is formatted as general or number. I explained as best I could why and to format the cell as text or add a single quote to the beginning, but she said it didn't work for her that way before. She has Word XP and I had several others try and it did...

Character Spacing Problems
When attempting to print in Publisher 2002 my text appears disjointed and expanded. if I use character spacing to correct this it only makes the printed copy worse! The text looks fine of the screen before I print but prints out all weird. Can anyone help me? It isn't a Publisher problem. It's most likely a printer driver problem. Go to the web site of the printer manufacturer and download the latest drivers. -- Ron Cohen drc023@ivwnet.com "Elizabeth" <beth@breadministries.org> wrote in message news:10fd01c34d43$5fdc0c30$3501280a@phx.gbl... > When attemptin...

Extracting Everything From Right of A Group of Characters
Hi all-- So I've got a field, and I need to extract all characters to the right of the group of characters -1\. I created a right function but it gives me some random result where -1\ is in the middle of the result. So I think I screwed something up. Any help? Thanks so much! EggHeadCafe - Software Developer Portal of Choice BizTalk Application that inserts records into SQL from *.CSV File http://www.eggheadcafe.com/tutorials/aspnet/6a535c9b-a5ee-46c8-9836-5dd6aefc6571/biztalk-application-that.aspx could do with nowing the following 1. Query that has the problem ...