简体   繁体   中英

Delete XML node that contains a certain value

Here is the xml structure. I am trying to delete each Status node where State contains the word failed. What is the best way to remove these?

<Stats>
    <Status>
        <Desc>something here</Desc>
        <State>pending - ok</State>
    </Status>
    <Status>
        <Desc>something here</Desc>
        <State>failed</State>
    </Status>
</Stats>

You can use Linq to XMl, to do the job

var xdoc = XDocument.Load(path_to_xml);

xdoc.Descendants("Status")
.Where(os => (int)os.Attribute("State") == "failed")
.Remove();

xdoc.Save(path_to_xml);
void Main()
{   
    XDocument xml = XDocument.Parse(@"<Stats>
    <Status>
        <Desc>something here</Desc>
        <State>pending - ok</State>
    </Status>
    <Status>
        <Desc>something here</Desc>
        <State>failed</State>
    </Status>
</Stats>");

    xml.Descendants("State").Where (x => x.Value.Contains("fail")).Ancestors("Status").Remove();
    Console.WriteLine(xml.ToString());  
}

Parse will load the xml in-memory, Load is used for loading it from a stream or via I/O means.

@Gregory Pilar's answer heavily influenced this answer; I believe he wrote that from memory, the snippet I provided was testing via LinqPad and returns expected results.

xDoc.Descendants("Status").Where(status => status.Element("State").Value.ToLower().Contains("fail")).Remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM