This is the co...">

How to collapse empty xml tags?

I get the XML as follows:

<Items> <Row attr1="val"></Row> <Row attr1="val2"></Row> </Items>

This is the correct XML, as you know, but the other library I use is disabled, and it will only accept XML in this format:

<Items> <Row attr1="val"/> <Row attr1="val2"/> </Items>

I already read XML in XmlDocuments, manipulating them and rewriting them with XmlWriter (), what is the easiest (and most efficient) way to "collapse" these empty tags?

+2
source share
5 answers

Set the IsEmpty property of each XmlElement that you want to collapse to the truth.

+4
source

If you use System.XML DOM object manipulation objects (XmlElement, etc.) instead of XmlWriter, you will get it for free.

XmlElement items = xmlDoc.SelectNodes("items");
XmlElement row = xmlDoc.CreateElement("row");
items[0].appendChild(row);

"< row/ > "

0

.

XmlTextWriter , WriteFullEndElement base.WriteEndElement. :

    public class BetterXmlTextWriter : XmlTextWriter
    {
        public BetterXmlTextWriter(TextWriter w)
            : base(w)
        {
        }

        public override void WriteFullEndElement()
        {
            base.WriteEndElement();
        }
    }

, XmlDocument.WriteContentTo.

0

XmlWriter XML, . ( .Net 3.5):

XmlWriter xw = XmlWriter.Create(Console.Out);
xw.WriteStartElement("foo");
xw.WriteAttributeString("bar", null, "baz");
xw.WriteEndElement();
xw.Flush();
xw.Close();

<foo bar='baz' />.

XmlWriter , , XmlWriter , .

0

:

private static void FormatEmptyNodes(XmlNode rootNode)
{
    foreach (XmlNode childNode in rootNode.ChildNodes)
    {
        FormatEmptyNodes(childNode);

        if(childNode is XmlElement)
        {
            XmlElement element = (XmlElement) childNode;
            if (string.IsNullOrEmpty(element.InnerText)) element.IsEmpty = true;
        }
    }
}

:

var doc = new XmlDocument();
doc.Load(inputFilePath);
FormatEmptyNodes(doc);
doc.Save(outputFilePath);
0

Source: https://habr.com/ru/post/1719285/


All Articles