Answered by:
Empty Elements with self closing tags

Question
-
I will like to add a self-closing tag to an empty elements using DOM C#
Example:
<tag test"ttt"> </tag>
<tag test"ttt"/>Tuesday, October 6, 2009 3:22 PM
Answers
-
Then you might want to try
XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("input.xml"); foreach (XmlElement el in doc.SelectNodes("descendant::*[not(*) and not(normalize-space())]")) { el.IsEmpty = true; } doc.Save("output.xml");
MVP XML My blog- Marked as answer by Marvelo Tuesday, October 6, 2009 7:24 PM
Tuesday, October 6, 2009 5:51 PM
All replies
-
If you have an XmlDocument instance doc then e.g
XmlElement foo = doc.CreateElement("foo"); foo.SetAttribute("test", "ttt");
creates an XmlElement node named "foo" whose IsEmpty property is set to true causing it to be serialized as <foo test="ttt" />.
So usually there is nothing you have to do, as long as the element has no child nodes it should be serialized the way you want. If it had child nodes and you have removed them then setting IsEmpty to true should help serialize them as you want.
MVP XML My blogTuesday, October 6, 2009 3:31 PM -
Thanks for your answer.
But How I add self-closing tags to all empty elements in a XML file.
Again
Thanks
MarveloTuesday, October 6, 2009 3:50 PM -
Does the following do what you want?
XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("input.xml"); foreach (XmlElement element in doc.SelectNodes("descendant::*[not(node())]")) { element.IsEmpty = true; } doc.Save("output.xml");
If not them you might want to post a small but representative sample of the XML you have and the corresponding output you want to create.
MVP XML My blogTuesday, October 6, 2009 3:56 PM -
Thanks
This is the example input
<publisher>
<agency name"test">
</agency>
<publisher>
<rights>
<privacy indicator"0">
</privacy>
<rights>
I want to create this output
<publisher>
<agency name"test"/>
<publisher>
<rights>
<privacy indicator"0"/>
<rights>Tuesday, October 6, 2009 4:35 PM -
Then you might want to try
XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load("input.xml"); foreach (XmlElement el in doc.SelectNodes("descendant::*[not(*) and not(normalize-space())]")) { el.IsEmpty = true; } doc.Save("output.xml");
MVP XML My blog- Marked as answer by Marvelo Tuesday, October 6, 2009 7:24 PM
Tuesday, October 6, 2009 5:51 PM -
This solution helped me , You can use this when u actually do not want to create an Xml and do not want to use Xml writer . Just use
doc.PreserveWhitespace = true;<br/>Before loading the Xml this will help to resolve the issue for self closing empty tag in xml.
Friday, November 4, 2016 5:19 AM