开发者

Badly formated XML generated by XElement.ReplaceWith()

开发者 https://www.devze.com 2022-12-17 07:42 出处:网络
I am trying to replace a node using ReplaceWith(), but noticed that it results in badly formated XML (missing new lines and indentations).

I am trying to replace a node using ReplaceWith(), but noticed that it results in badly formated XML (missing new lines and indentations).

Has anyone has come across this problem before?


Code Snippet:

[Test]
public void Test()
{
    XDocument document;

    using (var reader = XmlReader.Create("C:\\test.xml"))
    {
        // *** Running this line results in new lines OMITTED ***
        document = XDocument.Load(reader);

        // *** Running this line results in proper formatting ***
        //document = XDocument.Parse(XDocument.Load(reader).ToString());

    }

    var newNode = new XElement("Node", new XElement("SubNode"));

    document.Root.Element("Node").ReplaceWith(newNode);

    Console.Out.WriteLine("document = {0}", document);
}

Steps to Reproduce:

1) Create C:\test.xml with the following:

<Test>
    <Node/>
<Test>

2) Run the code snippet above.

This will result in some in some improperly formated XML:

<Test>
    <Node><SubNode /></Node>
</Test>

3) Uncomment this line:

document = XDocument.Parse(XDocument.Load(reader).ToString());

4) Run the snippet again.

The result will be properly formatted:

<Test>
  <Node>
    <SubNode />
  &开发者_StackOverflow中文版lt;/Node>
</Test>


Though XElement / XDocument "nicely" formats xml implicitely while parsing it (using .Parse()), it does not seem to have a method to explicitly pretty-print its content. This would actually be a nice addition to the .net framework.

The hack you specified, though not very efficient, is a quick way of doing it:

XDocument.Parse(XDocument.Load(reader).ToString());


The result is valid XML. Newlines and indentation does not matter in XML.

If you need it pretty-printed, you do that after you're done manipulating the XML.

0

精彩评论

暂无评论...
验证码 换一张
取 消