.Elements()
will only return direct child elements.
You want .Descendants()
, which returns all nested elements.
searching for an unnamed nested XElement by a specific XAttribute
-
31-05-2022 - |
Question
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();
No correct solution
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow