2010-03-17 69 views
10

我有一个的XDocument,看起来像这样:强制XDocument.ToString()包括结束标记时,有没有数据

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

那当我打电话

outputDocument.ToString() 

输出到这一点:

<Document> 
    <Stuff /> 
</Document> 

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

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

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

回答

12

将每个空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; 
     } 
    } 
+0

谢谢!我在正确的道路上,试图将一个String.Empty放在XDocument声明中,但显然它在那里被忽略。 – 2010-03-17 19:36:38

+0

我们如何才能完成逆向转换?即代替我希望看到。 – Kamyar 2018-03-10 01:52:45

相关问题