How to remove closing tag of an XmlDocument in C#, .NET 1.1?

ぃ、小莉子 提交于 2019-12-25 06:40:28

问题


How can I remove the closing tag of element c in a XML document?

The converted XML will go through a schema validation and it is rejected because it has a whitespace within. I'm using C#, .NET 1.1 (I'm updating a legacy application :-( ).

Note: I must not resort to string manipulation to convert the XML document.

Current:

<main>
  <a>
    <b />
    <c>
    </c>
  </a>
</main>

Final:

<main>
  <a>
    <b />
    <c />
  </a>
</main>

Update 1: for additional details, the final XML document is saved as file, and then another process validates the file. It appears that the saved XML is formatted.

I'm not sure if this is true:

<a></a> == <a />

回答1:


Maybe setting InnerText to null instead of string.Empty would help?

Update. Or just set XmlElement.IsEmpty )




回答2:


Try this:

XmlDocument xml = new XmlDocument();
xml.LoadXml(@"
 <main>
  <a>
    <b />
    <c>
    </c>
  </a>
</main>");

foreach(XmlElement element in xml.SelectNodes("//*[. = '' and count(*) = 0]"))
{
    element.IsEmpty = true;
}

Console.WriteLine(xml.InnerXml);
Console.ReadLine();


来源:https://stackoverflow.com/questions/2107909/how-to-remove-closing-tag-of-an-xmldocument-in-c-net-1-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!