views:

148

answers:

1

Hi,

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 />
  </Node>
</Test>
A: 

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.

John Saunders
To be fair, he didn't actually claim it was invalid.
Mike Powell
@Mike: true - I'm just emphasizing that it's valid, and that he should either get over the "format", or else explicitly format it himself, when he needs it pretty-printed.
John Saunders
@John: It is indeed valid XML. But I didn't expect ReplaceWith() to mess up the format at the same time!
stung
@stung: XML doesn't have format. Strings have formats. It's possible to produce a formatted string from XML. `XElement` does not represent a string - it represents an XML element.
John Saunders
@John: You're totally correct. Somehow I thought XElement internally keeps the XML tidy. My mistake for that assumption. However, it IS weird how a XDocument constructed by a XmlReader format differently than a XDocument constructed by a XML string. But if that's just the way it is, I'm good with it too as long as it's clear.
stung
@John: btw, are there any classes in the framework that helps tidy xml?
stung
@stung: you've already used it - `XElement.ToString`.
John Saunders
@stung: in general, you don't want tidy XML. "tidy" is something for humans. Code doesn't care about "tidy".
John Saunders