强制XDocument.ToString()在没有数据时包含闭合标签

14

我有一个像这样的XDocument:

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

当我调用这个函数时

outputDocument.ToString()

输出为:

<Document>
    <Stuff />
</Document>

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

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

我知道第一个是正确的,但是我必须以这种方式输出它。有什么建议吗?

2个回答

17

将每个空的XElementValue属性明确设置为空字符串。

    // 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;
        }
    }

谢谢!我走在正确的道路上,试图在XDocument声明中放置一个String.Empty,但显然它会被忽略。 - Jason More
我们如何完成反向转换?即,我想看到<Stuff/>而不是<Stuff></Stuff>。 - Kamyar

0

在使用XNode.DeepEquals时遇到了一个问题,当存在空标签时,另一种比较XML文档中所有XML元素的方法(即使XML关闭标签不同也可以正常工作)

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);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接