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

Similar Articles

[PageSpeed] 43

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:

can we attach an image file to a excel cell ,like note pad comment
can we attach an image file to a excel cell ,scanned with a scanner ,like note pad comment ?I have a small database with 50-60 names and i need to save the letters written to each of those names .Please help. You can put the image in a comment: http://www.contextures.com/xlcomments02.html#Picture In article <66D49CAB-F151-42C9-8E55-E5CFC9CF3855@microsoft.com>, "PR" <PR@discussions.microsoft.com> wrote: > can we attach an image file to a excel cell ,scanned with a scanner ,like > note pad comment ?I have a small database with 50-60 names and i need to sav...

how do i delete everything after a particular character, after each such character?
i have about 1,800 rows of text data, some of which need to be cleane as follows: about 2/3 of the 1,800 rows have text that appears after a dash whic is preceded and followed by a space (" - ") and this post-dash tex needs to be deleted. ideally, there would be some way to tell excel to check each cell t see whether there is a " - " in the text data and, if there is, t delete the dash and everything AFTER the dash (but nothing before it) this way, all cells containing no dash at all remain unaffected, an the cells containing a dash lose everything that appears after th ...

Does SQL Server need compacting like MSAccess databases?
I have a database on a shared SQL 2005 server at www.serverintellect.com It is currently limited to 250 MB. I have a stored procedure that runs every 15 minutes. It deletes all records from a table and then inserts records again on the same table. If this was MSAccess, the file size of the database would increase every 15 minutes by the size of the insert. Does the same apply to SQL Server 2005? On Jul 15, 4:59=A0am, "Mark B" <none...@none.com> wrote: > I have a database on a shared SQL 2005 server atwww.serverintellect.com > > It is currently limi...

Problem with email encoding
Hello all!! Five months ago we migrated from exchange 5.5 to exchange server 2003.Now , we detect the following problem: in several cases , when a user send a mail with ñ letter in the other side they can only see stange characters.The exchange 2003 languaje installation is English , bur the regional settings are spanish traditional.We dont understand whats happend...... Any idea??? Thanks in advance........ ...

FIND SPECIAL CHARACTERS
Hi, I am trying to find character "*" and replace them in my spreadsheet. However, whenever I did, all were replaced. Is there a way of typing in order that the program know I am actually searching for the character "*" only ? Thanks. Rgds, Frankie Search for: ~* Biff "Frankie" <Frankie@discussions.microsoft.com> wrote in message news:C3DC1558-2670-41CD-92A3-66791B2DA573@microsoft.com... > Hi, > > I am trying to find character "*" and replace them in my spreadsheet. > However, whenever I did, all were replaced. > Is there a w...

I have a Comma Delimited FIle that requires 10 characters for name
I use Excel a lot, but am by no means fluent with it. I'm trying to create a ..csv file, I have columns set up with (thousands) names, and those cells have to have 10 characters regardless of actual name length. Is there a way to do that without me having to space after each name? Also, is there a way to split a full name (ex. LASTNAME,FIRSTNAME,MI) into three seperate columns? They are seperated by a space, but all are contianed in the first column. If you using Excel 2003, try Data-Text to columns "sueshe" wrote: > I use Excel a lot, but am by no means fluent wit...

sum of characters
What is the formula for finding the total number of letters in a range of cells? Example - How many x's and how many t,s in cels A1:G1. For the number of x's... =COUNTIF(A1:G1,"x") For the number of x's and t's... =SUMPRODUCT(--(ISNUMBER(MATCH(A1:G1,{"x","t"},0)))) Hope this helps! In article <1DE605A0-6B92-4D76-A477-609FFFAA2118@microsoft.com>, ddwchs <ddwchs@discussions.microsoft.com> wrote: > What is the formula for finding the total number of letters in a range of > cells? Example - How many x's and how many t,s ...

How do I change word spacing (two characters) to (one character)?
I have a word document which has word spacing (two characters), How do I change the word spacing to (one character) automatically preferably? Since the document is 70 plus pages doing it by using the "spell and grammar check" is going to take hours. I'm using word 2002. Look under Tools, Options, Spelling & Grammar, Settings button, Spaces required between sentences: change to 1. This will now indicate any sentence spacings that are more than 1 as a grammar error. To change the existing double spacing you can easily use the Replace function to change double sp...

MS Query. Can you use parameters with LIKE and % wildcards?
Please help! I have (what I thought was) a very simple single table query, but I am struggling with it in MS Query. I can do it using stored procedures and ADO, but that would probably be overkill for such a small query and I will only resort to that if somebody confirms that is impossible to achieve using MS Query My problem is that the parameter that the users will enter (location code) is a substring of item code in the table. There can be more than 1 item code with the same location code embedded in it and this is what the report seeks to identify. However the location code substring ...

"Special" Catagories in Savings/CC Account
There's a "Special" section of catagories in my checking account that I imported from online that contains transfer & credit card payment categories but they're not available in my credit card account & savings account that I import or a 2nd checking account that i have to input manually. Is there a way to change that or am I stuck with it? Convert all accounts to Advanced Register on their settings pages. All will be good. Indeed, convert Essential * to Advanced *. Essential * are for the computer challenged. You've found your way to the newsgroup, sort ...

clean characters
i have a file with multiple rows and columns and since it is a download from another application, it has some unprintable characters. I have been using the clean function to do one column at a time. Is there a faster way to do this? Not all rows have values populated for all columns, so i have to drag down the formula for each column Hi Bookworm, See David McRitchie's TrimAll macro at: http://www.mvps.org/dmcritchie/excel/join.htm#trimall If you are unfamiliar with macros, see David's 'Getting Started With Macros and User Defined Functions' page at: ht...

Can you add a KPI that works like a speedometer?
Dear all, I want to visualize our performance in a speedometer like KPI. Which looks like below with a needle to point the status 100% 95% .. ..105% .. .. 75%.. .. 125% In awaitence of your reply. Thanks in advance Mark Sterckel Customer Service manager ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this sugg...

Patches I'd like to see for Outlook 2003.
1 Search results with logical fields. If I search through my SENT items for the word "status report" (or any other term) it should display the sent TO field. It always displays the from field - it is my sent items I'm searching so guess what, they are always from me! I can add the field after the search but it would make sense for it always to display the TO field. 2 The ability to open more than one outlook profile simultaneously. 3 Block domain for junk mail. Not sure why I can add an entire domain to a safelist but not block an entire domain - seems odd or if it exi...

Special Query
I have a table with following 3 fields: Account_1, Account_2, Amount Any query that would result into following layout? Account (Containing Unique Names From BOTH Account_1, Account_2) Amount_1 (Containing Amounts of Accounts Listed In Account_1) Amount_2 (Containing Amounts of Accounts Listed In Account_2) For instance, consider the following sample: Account_1, Account_2, Amount ====== ======= ===== AccountA AccountB 1000 AccountC AccountA 2000 AccountB AccountC 3000 To be generating a result as follows: Account, Amount_1, Amount_2 =====...

Generating Unicode characters in a cell using formulas
With older multibyte Chinese code sets like Big5, I could create a large list or table of Chinese characherts by generating their two components with a formula like =CHAR(HEX2DEC(LEFT(A5,2)))&CHAR(HEX2DEC(RIGHT(A5,2))) were the hex code for the character (eg. A440) was in tyhe target cell A5. With Unicode, all I get are the two individual characters that (in Big5 anyway) made up the multi-byte code for a character. BTW: In the case above, Big5 A440 is Unicode U+4e00, the character for "one" 一. Hi Geoff, You will have to create a User Defined Function for use on your w...

Edit box should support languages like japanese,chineese etc
Hi wht im trying to ask is.. 1. In my application, all the labels r in english only. 2.If i change the content of one text box in japanese or chineese language , [Text box value is the title for another dialog] 4.After i changed the content, i want the title to be displayed in japanese or chineese language. Note: I want only that text box to be changed ,,not the entire application.. so How can i able to support multibyte characters in MFC controls CEdit --text boxes.. Plz reply They do. You have to be in a Unicode app, and you have to have selected a Unicode font that has Chin...

previewing attachments in Outlook xp in the preview pane like OE
I finally got my wife to use Outlook over Outlook Express, but one feature she really wants is to be able to see attachments like pictures etc in the body of the message in the preview pane like she could in Outlook Express. I have been unable to find where I can allow this. Anyone have any ideas? By design, Outlook does not display attached images inline. Outlook is a business application. OE is targeted to consumers and the needs of the two groups are different in this area. Exchange Administrators consider inline display a security issue and don't want it. Outlook only shows i...

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. Set your Excel font to the same as the Notepad font. Otherwise there is no way to measure the length. "ktuprah" <ktuprah@hotmail.com> wrote in message news:OCs3$01dKHA.4780@TK2MSFTNGP04.phx.gbl... > Is there anyway to specify a certain character length when defining a > column in excel? The worksheet in excel has to be exporte...

Color Index Code, is there any thing like that?
I have a question regarding the color in Excel. In normal time, if I want the negative number shown in Red color, then I will formate a cell with【#, ##0;[Red] (#,##0)】. My question is that what happen if I want some other color apart from the mainstream color (e.g black, green etc), how can I easily formate it? What I mean is there any special color index code which I can fill to the Excel formula, instead of just put [Red]. Many thanks, Wilchong -- Message posted via http://www.officekb.com Try # ##0;[Color n] (#,##0) Where n is the number of a colour in the Excel colour palette...

Converting characters to text strings
To easily generate texts, I would like to translate text codes into text strings. If A translates into "Text A", B into "Text B" etc, then I would like these texts entered into a column to be shown like this: A "Text A" ABC "Text A, Text B, Text C" BC "Text B, Text C" The triggy issue for me is that I do not know how many characters there are in each string to be translated. It could be 1 or it could be 10. Mogens Use VLOOKUP Make a table with the code in the first column and the full text in the second. Then the VLOOKUP function ca...

Importing text files with mathematical characters
I am importing text files to Excel and they contain mathematical operators as part of the data. (For example "++" to denote a quantity of something.) Excel will not allow these characters as it thinks they are mathematical. Is there any way of stopping this happening? Thanks in advance "The Beckster" <The Beckster@discussions.microsoft.com> wrote in message news:07D6533B-0C29-4287-9ECE-A337DE39DB8D@microsoft.com... > I am importing text files to Excel and they contain mathematical operators as > part of the data. (For example "++" to denote a quant...

Error found while running "Perform Special Upgrade" in Utility
After installing HR and Manufacturing into my GP 8.0, I got missing Stored Procedure error message. Therefore I went to GP Utility program to perform special upgrade for trying to add additional stored procedure. However; after I clicked on "Process" and "Update" button, I got the following error messages, does anyone know how to solve it? Error message 1: The following SQL statement produced an error: GRANT SELECT , UPDATE , INSERT , DELETE ON [dbo].[IVR10015] TO [DYNGRP] Error message 2: ERROR [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object n...

How do I increase query field length (>20 characters) ?
I want to exclude 3 or 4 variables from a particular query. Using Not "xx"or"yy" is fine, but when excluding more than this, query fails. I think the problem is that the total text characters is quite large (approx 60 characters in total, from four exclusions). Ideas, please ? 60 characters is not the limit. 1024 characters is the limit. POST the SQL of the query that is not working (View: SQL on the menu) or at a minimum post what you are attempting as the criteria. Also "query fails" does not tell us if you get an error (what is it) or the wrong resul...

Max. number of characters to be shown in one celle?
H I hope somebody can tell me, if there is a max. number of characters, there can be shown in one celle When I write a long text, the celle shows only ##### no matter how much I enlarge the celle. I can still see the original text in the formula line, but it can not be shown in the spread sheet, and I can not copy it to word. According to the specifications (Help/Specifications) each cell can hold a maximum of 32,767 characters, of which 1024 can be displayed. If you enter a manual line break within the first 1024 characters, (alt-Enter), you can get more than that. In article <8253B...

How do I make 1 and 1/2 cups look like 1 1/2?
I do not want it to look like eleven. How do I make the 1/2 part look better to create one and one half cups? Alt+0189 or Insert, symbol... -- Mary Sauer MSFT MVP http://office.microsoft.com/ http://msauer.mvps.org/ news://msnews.microsoft.com "Shelby" <Shelby@discussions.microsoft.com> wrote in message news:CDAA93B5-3197-4908-B67D-076DDAF05E81@microsoft.com... >I do not want it to look like eleven. How do I make the 1/2 part look better > to create one and one half cups? Shelby wrote: > I do not want it to look like eleven. How do I make the 1/2 part look be...