문제

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();

올바른 솔루션이 없습니다

다른 팁

.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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top