Search code examples
xmlxml-parsinglinq-to-xmlxmldocument

How to Make XDocument keep new line in attributes like XmlDocument does?


I am using XDocument and LINQ with great ease and comfort, but
one problem arises:

XDocument removes new lines inside attribute when you try to output back the xml.
XmlDocument on the other hand, keeps the new line.

static void Main(string[] args)
{
    string res;
    string str = "<element attrib='Some text \n with new line'/>";

    XDocument xDoc = XDocument.Parse(str);
    res = xDoc.ToString();
    //res dose not containe the new line.

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(str);
    res = xmlDoc.OuterXml;
    //res contains a new line char, that i can replace to something more nice like /r.
    res = res.Replace("&#xA;", Environment.NewLine);
}

I have a lot of code already written with XDocument, and don't want to rewrite it using XmlDocument. How can I get XDocument to behave like XmlDocument it this manner?


Solution

  • According to the XML specification attribute value are normalized when parsing a document. The normalization replaces all newline character in attribute values with blank characters (#x20). Note that this normalization happens already when you create the XDocument, not when you write it back to a file and that it is totally conformant to the XML specification.

    If you want to retain the newline, you could encode the newline as &#xA; in your input:

    var inputXml = "<element attrib='Some text &#xA; with new line'/>";
    var xDoc = XDocument.Parse(inputXml);
    var attribValue = (string)xDoc.Root.Attribute("attrib");