views:

287

answers:

2

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 />
+2  A: 

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

Update. Or just set XmlElement.IsEmpty )

Dmitry Ornatsky
Hi, thanks for answering but it did not solved the issue. It seems that the final xml document is formatted, hence white space is added.I'll add more details on the issue I've encountered.
OnesimusUnbound
have you seen the update?
Dmitry Ornatsky
Thanks, it worked. Actually I was using XmlNode, not XmlElement, hence the solution is not obvious. I've set the c node as an XmlElement, and not just XmlNode.
OnesimusUnbound
+3  A: 

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();
Rubens Farias