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

问题描述 投票:11回答:2

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

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

当我打电话时

outputDocument.ToString()

输出到此:

<Document>
    <Stuff />
</Document>

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

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

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

c# .net linq linq-to-xml
2个回答
13
投票

将每个空ValueXElement属性设置为专门的空字符串。

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

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);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.