views:

28

answers:

2

Hi, I am trying to generate a xml document using LinqXml, which has the "\n" to be "& #10;" in the XElement value, no matter whatever settings I try with the XmlWriter, it still emits a "\n" in the final xml document.

I did try the following, Extended the XmlWriter. Overrided the XmlWriterSettings changed the NewLine Handling. Both of the options didnt work out for me.

Any help/pointers will be appriciated.

Regards Stephen

A: 

What is the reason for having the escaped value for '\n' in the XML element? The newline character is valid inside an XML element and when you parse the XML again, it will be parsed as you expect.

What you're looking for would happen if the newline character is placed within the value of an XML attribute:

        XElement xEl = new XElement("Root", 
            new XAttribute("Value", 
                "Hello," + Environment.NewLine + "World!"));

        Console.WriteLine(xEl);

Output:

<Root Value="Hello,&#xD;&#xA;World!" />
Mike
Thanks for the quick reply, the Attribute works well but I wanted to retain the newline information in the XElement Value in form of entity.
StevenzNPaul
+1  A: 

LINQ to XML works on top of XmlReader/XmlWriter. The XmlReader is an implementation of the XML processor/parser as described in the XML spec. That spec basically says that the parser needs to hide the actual representation in the text from the application above. Meaning that both \n and should be reported as the same thing. That's what it does.

XmlWriter is the same thing backwards. It's purpose is to save the input in such a way, that when parsed you will get exactly the same thing back. So writing a text value "\n" will write it such that the parser will report back "\n" (in this case the output text is \n for text node, but for attribute due to normalization which occurs in attribute values). Following that idea trying to write a text value " " will actually write out "&#10;" because when the reader parses that it will get back the original " ".

LINQ to XML uses XmlWriter to save the tree to an XML file. So you will get the above behavior.

You could write the tree into the XmlWriter yourself (or part of it) in which case you get more control. In particular it will allow you to use the XmlWriter.WriteCharEntity method which forces the writer to output the specified character as a character entity, that is in the $#xXX; format. (Note that it will use the hex format, not the decimal).

Vitek Karas MSFT
Thanks, this makes sense.
StevenzNPaul