Forcing XDocument.ToString() to include the closing tag when there is no data
Asked Answered
F

2

14

I have a XDocument that looks like this:

 XDocument outputDocument = new XDocument(
                new XElement("Document",
                    new XElement("Stuff")
                )
            );

That when I call

outputDocument.ToString()

Outputs to this:

<Document>
    <Stuff />
</Document>

But I want it to look like this:

<Document>
    <Stuff>
    </Stuff>
</Document>

I realize the first one is correct, but I am required to output it this way. Any suggestions?

Fabiolafabiolas answered 17/3, 2010 at 0:21 Comment(0)
E
17

Set the Value property of each empty XElement specifically to an empty string.

    // Note: This will mutate the specified document.
    private static void ForceTags(XDocument document)
    {
        foreach (XElement childElement in
            from x in document.DescendantNodes().OfType<XElement>()
            where x.IsEmpty
            select x)
        {
            childElement.Value = string.Empty;
        }
    }
Eider answered 17/3, 2010 at 0:42 Comment(2)
Thanks! I was on the right path, trying to put a String.Empty in the XDocument declaration, but apparently it gets ignored there.Fabiolafabiolas
How can we accomplish the reverse transformation? i.e instead of <Stuff></Stuff> I would like to see <Stuff/>.Cherey
B
0

an issue using the XNode.DeepEquals when there is an empty tags, another way to compare all XML elements from XML documents (this should works even if the XML closing tags are different)

public bool CompareXml()
{
        var doc = @"
        <ContactPersons>
            <ContactPersonRole>General</ContactPersonRole>
            <Person>
              <Name>Aravind Kumar Eriventy</Name>
              <Email/>
              <Mobile>9052534488</Mobile>
            </Person>
          </ContactPersons>";

        var doc1 = @"
        <ContactPersons>
            <ContactPersonRole>General</ContactPersonRole>
            <Person>
              <Name>Aravind Kumar Eriventy</Name>
              <Email></Email>
              <Mobile>9052534488</Mobile>
            </Person>
          </ContactPersons>";

    return XmlDocCompare(XDocument.Parse(doc), XDocument.Parse(doc1));

}

private static bool XmlDocCompare(XDocument doc,XDocument doc1)
{
    IntroduceClosingBracket(doc.Root);
    IntroduceClosingBracket(doc1.Root);

    return XNode.DeepEquals(doc1, doc);
}

private static void IntroduceClosingBracket(XElement element)
{
    foreach (var descendant in element.DescendantsAndSelf())
    {
        if (descendant.IsEmpty)
        {
            descendant.SetValue(String.Empty);
        }
    }
}
Barringer answered 23/2, 2020 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.