Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 691
Jason More Avatar asked Mar 17 '10 00:03

Jason More


1 Answers

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;
        }
    }
like image 161
Jason Kresowaty Avatar answered Oct 20 '22 14:10

Jason Kresowaty