强制XDocument.ToString()在没有数据时包含结束标记

Jas*_*ore 11 .net c# linq linq-to-xml

我有一个看起来像这样的XDocument:

 XDocument outputDocument = new XDocument(
                new XElement("Document",
                    new XElement("Stuff")
                )
            );
Run Code Online (Sandbox Code Playgroud)

那我打电话的时候

outputDocument.ToString()
Run Code Online (Sandbox Code Playgroud)

输出到:

<Document>
    <Stuff />
</Document>
Run Code Online (Sandbox Code Playgroud)

但我希望它看起来像这样:

<Document>
    <Stuff>
    </Stuff>
</Document>
Run Code Online (Sandbox Code Playgroud)

我意识到第一个是正确的,但我需要以这种方式输出它.有什么建议?

Jas*_*aty 13

Value每个空的属性XElement专门设置为空字符串.

    // 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)