Domanda

Here is what my XML looks like (Yes, I know the XML is ugly). I'm trying to search and remove any nodes from this XDocument that have the isConstField attribute set to "Y" without iterating through each individual XElement.

<Root>
    <Node>
        <SubNode>
            <SubNode2>
                <FieldNameA isConstField="Y"></FieldNameA>
                <FieldNameB></FieldNameB>
                <FieldNameC isConstField="N"></FieldNameC>
            </SubNode2>
        </SubNode>
        <SubNode>
            <SubNode2>
                <FieldNameD></FieldNameD>
                <FieldNameE></FieldNameE>
                <FieldNameF></FieldNameF>
            </SubNode2>
        </SubNode>
    </Node>
</Root>

Here is how I'm trying to do it

XDocument doc = XDocument.Load(@"d:\junk\Test\Test\Data.xml");
doc.Descendants("Root").Elements().Where(x => (string)x.Attribute("isConstField") == "Y").Remove();

Nessuna soluzione corretta

Altri suggerimenti

.Elements() will only return direct child elements.
You want .Descendants(), which returns all nested elements.

You can do it with XPath extensions (don't forget to add System.Xml.XPath namespace reference):

doc.XPathSelectElements("//*[@isConstField='Y']").Remove();

Expression matches any node which have isConstField attribute equal to Y. XPathSelectElements selects all such nodes. And then all selected nodes are removed.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top