Reputation: 4231
I have an XML File of this sort
<BallList>
<Brand name="xyz">
<BallName>ball A</BallName>
<DateApproved>Jan-12</DateApproved>
<link>www.a.com</link>
</Brand>
<Brand name="abc">
<BallName>Ball B</BallName>
<DateApproved>Jan-02</DateApproved>
<link>www.b.com</link>
</Brand>
</BallList>
In This way there are around 150 brands and 8000 ball names. I know this is not a good way to represent the XML, but now as the data is huge, structure cannot be modified.
I need to delete "Brand" node by comparing it with its ballname
Here is the code that I am trying out:
XElement doc = XElement.Load(Server.MapPath("NetBalls.xml"));
doc.Elements("Brand")
.Where(s => s.Attribute("name").Value == DropDownList1.SelectedItem.Text)
.Elements("BallName")
.Where(l => l.Value == textbox1.Text)
.AncestorsAndSelf()
.Remove();
I am trying to search for brand and go into its element node and check its node and delete its parent.
Can anyone help me with this?
Upvotes: 3
Views: 2313
Reputation: 18137
string brandName = "xyz";
string ballName = "ball A";
var brands = doc.Elements("Brand").Where(s => s.Attribute("name").Value == brandName);
foreach (var brand in brands)
{
if(brand.Elements("BallName").Any(l => l.Value == ballName))
{
brand.Remove();
}
}
Upvotes: 1
Reputation: 385
You can combine the selection criteria in a single where clause:
doc.Elements("Brand")
.Where(brand =>
(string)brand.Attribute("name") == DropDownList1.SelectedItem.Text &&
brand.Elements("BallName").Any(ballName => (string)ballName == textbox1.Text))
.Remove();
Upvotes: 1
Reputation: 28338
Instead of navigating down to the child nodes and back up again, just embed the child-level criteria in a Where
query against the elements you actually want:
doc.Elements("Brand")
.Where(s => s.Attribute("name").Value == selectedBrand)
.Where(s => s.Elements("BallName").Any(l => l.Value == selectedValue))
.Remove();
This way, your Linq query more closely matches your English query: "Find me all of the Brand elements where the name attribute is x, and their Ballname element is y, and remove it."
Upvotes: 3
Reputation: 39620
You want to remove the brand element? Try this:
xml.Elements("Brand")
.Where(s => s.Attribute("name").Value == DropDownList1.SelectedItem.Text)
.Elements("BallName")
.Where(l => l.Value == textbox1.Text)
.Select(x => x.Parent)
.Remove();
This will remove all Brand elements where the conditions apply.
Upvotes: 1