【问题标题】:Forcing XDocument.ToString() to include the closing tag when there is no data没有数据时强制 XDocument.ToString() 包含结束标记
【发布时间】:2010-03-17 00:21:28
【问题描述】:

我有一个如下所示的 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


    【解决方案1】:

    将每个空的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,但显然它在那里被忽略了。
    • 如何完成逆向转换?即,而不是 我想看到 .
    【解决方案2】:

    存在空标签时使用 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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-28
      • 2010-12-26
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2011-05-24
      相关资源
      最近更新 更多