Reputation: 47
first, sorry for my bad english, i'm learning yet. So, I have to delete specifics nodes of a xml file according with their attributes. This is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
<Indice value="72">
<Palavra value="cristiano" />
<Significados>ornelas,ribeiro,,,</Significados>
</Indice>
<Indice value="72">
<Palavra value="teste2" />
<Significados>s2,s3,,,</Significados>
</Indice>
</Lista>
I have to delete all Indice nodes and your childrens that have the attribute value="72" for example. How can I do that? The language is c# and the xml file after of delete must stay in this form:
<?xml version="1.0" encoding="utf-8"?>
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
</Lista>
Upvotes: 2
Views: 872
Reputation: 2192
This is an alternative to Spender although he should get the question answered if his works.
XmlDocument doc = new XmlDocument();
doc.Load("xml path");
XmlNode node = doc.SelectSingleNode("/Lista");
foreach (XmlNode nodes in node.SelectNodes("Indice/@value"))
{
if (nodes.Value == "72")
{
nodes.RemoveAll();
}
}
Upvotes: 0
Reputation: 120508
XDocument xdoc=XDocument.Parse(xmlStr); //or XDocument.Load
var matchingElements = xdoc.Root
.Descendants("Indice")
.Where(e => (int)e.Attribute("value") == 72)
.ToList();
foreach(var elem in matchingElements)
{
elem.Remove();
}
xdoc.Save(newFileName);
saves the following doc:
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
</Lista>
Upvotes: 2