Home > Software design >  Parse XML skipping attributes if it does not start with * in c#
Parse XML skipping attributes if it does not start with * in c#

Time:01-03

I have written something small to output an xml file from and xml file, the output will only contain nodes that are required using xpath, I'm happy with this.

As an example below; I would like to expand this further and specifically output ALL of the input XML but in node QWE @ID skip any attribute that does not start with AA.

I have tried this with xpath with no luck. I believe I will need to do this in a loop.

Gentle please, we all start out somewhere.

Thanks.

<MMM>
    <PPP>
        <AAA>
            <QWE ID="AABBCC">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
                <NAME3>CC</NAME3>
            </QWE>
            <QWE ID="AACCBB">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
                <NAME3>CC</NAME3>
            </QWE>
            <QWE ID="CCDDKK">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
                <NAME3>CC</NAME3>
            </QWE>
            <QWE ID="CCKKDD">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
                <NAME3>CC</NAME3>
            </QWE>
        </AAA>
        <BBB>
            <RTY ID="ASDF">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
            </RTY>
            <RTY ID="ASDG">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
            </RTY>
            <RTY ID="ASDH">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
            </RTY>
            <RTY ID="ASDJ">
                <NAME1>AA</NAME1>
                <NAME2>BB</NAME2>
            </RTY>
        </BBB>
    </PPP>
</MMM>
XmlNodeList nodes = doc.SelectNodes("/*");

XmlElement root = newDoc.CreateElement("MMM");
newDoc.AppendChild(root);

foreach (XmlNode node in nodes)
{
    if (node.Name == "QWE")
    {
        XmlElement newElement = newDoc.CreateElement(node.Name);
        root.AppendChild(newElement);

        foreach (XmlAttribute attribute in node.Attributes)
        {
            if (attribute.Name == "ID" && attribute.Value.StartsWith("AA"))
            {
                XmlAttribute newAttribute = newDoc.CreateAttribute(attribute.Name);
                newAttribute.Value = attribute.Value;
                newElement.Attributes.Append(newAttribute);
            }
        }
    }
    else
    {
        root.AppendChild(newDoc.ImportNode(node, true));
    }
}

CodePudding user response:

You can use Linq to XML:

var doc = XDocument.Load(@"yourfile.xml");
doc.Descendants("QWE")
    .Where(x => !x.Attribute("ID").Value.StartsWith("AA"))
    .Remove();
doc.Save("output.xml");
  • Related