首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >强制XDocument.ToString()在没有数据时包含结束标记

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

Stack Overflow用户
提问于 2010-03-17 08:21:28
回答 2查看 3.7K关注 0票数 14

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

代码语言:javascript
运行
复制
 XDocument outputDocument = new XDocument(
                new XElement("Document",
                    new XElement("Stuff")
                )
            );

当我打电话给

代码语言:javascript
运行
复制
outputDocument.ToString()

输出结果如下:

代码语言:javascript
运行
复制
<Document>
    <Stuff />
</Document>

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

代码语言:javascript
运行
复制
<Document>
    <Stuff>
    </Stuff>
</Document>

我意识到第一个是正确的,但我需要这样输出它。有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-03-17 08:42:04

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

代码语言:javascript
运行
复制
    // 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;
        }
    }
票数 16
EN

Stack Overflow用户

发布于 2020-02-23 16:22:30

当存在空标记时使用XNode.DeepEquals是一个问题,这是比较XML文档中所有XML元素的另一种方法(即使XML结束标记不同,这种方法也应该有效)。

代码语言:javascript
运行
复制
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);
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2459138

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档