James
James

Reputation: 1392

Delete xElement by xAttribute value

I have the following xml document:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <title>
    <Type name="James">
      <Field name="ref" value="79" />
      <Field name="titleref" value="55" />
    </Type>
  </title>
</Categories>

I want to delete all of 'title' if the textBox1 text matches

I have the following, I know it doesn't work, but I wanted to see if you can see my logic.

 xmldoc.Root.Elements().Where(x => x.Element("Type")).Where (x => x.Attribute("name").Value.Equals(textBox1.Text)).Select(x => x).Single().Remove();

Any help would be great

Thanks

Upvotes: 1

Views: 319

Answers (2)

I4V
I4V

Reputation: 35353

You can use XPath (System.Xml.XPath)

xmldoc.XPathSelectElements(String.Format("//Type[@name='{0}']", textBox1.Text))
      .Remove();

Upvotes: 2

Metro Smurf
Metro Smurf

Reputation: 38335

xmldoc.Root.Descendants( "Type" )
  .Where( x => x.Attribute( "name" ).Value == textBox1.Text )
  .Remove();

Upvotes: 0

Related Questions