.NET:如何将空XML节点写为&#34; <node> </node>&#34;而不是&#34; <node>&#34;

时间:2016-05-26 10:59:02

标签: .net xml

我使用通常的对象(XmlDocumentXmlElement等)在.net中构建xml文档,最后将其输出为字符串(xmlDocument.OuterXml)。

在最终输出中,所有没有innerXml的空xml元素都被写成这样 - <node />

虽然我特别需要这样写 - <node></node>

有没有办法用.NET对象执行此操作?我想我可以用Regex替换最后一个字符串中的相关元素,但我希望有一个更干净的方法。

1 个答案:

答案 0 :(得分:0)

您只需将空文本节点添加到空元素即可。

以下是使用XDocument的示例:

var doc = new XDocument(new XElement("root", new XElement("test", "hello world"), new XElement("foobar", new XElement("empty"), new XElement("has_attrs", new XAttribute("test", "123")))));
Console.WriteLine(doc.ToString());
<root>
  <test>hello world</test>
  <foobar>
    <empty />
    <has_attrs test="123" />
  </foobar>
</root>
foreach (var empty in doc.Descendants().Where(e => string.IsNullOrEmpty(e.Value) && !e.Attributes().Any()))
{
    empty.Add(string.Empty);
}
Console.WriteLine(doc.ToString());
<root>
  <test>hello world</test>
  <foobar>
    <empty></empty>
    <has_attrs test="123" />
  </foobar>
</root>
相关问题