通过xAttribute值删除xElement

时间:2012-12-15 22:28:57

标签: c# xml linq-to-xml

我有以下xml文档:

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

如果textBox1文本匹配

,我想删除所有'标题'

我有以下内容,我知道它不起作用,但我想知道你是否能看到我的逻辑。

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

任何帮助都会很棒

由于

2 个答案:

答案 0 :(得分:2)

您可以使用XPath(System.Xml.XPath)

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

答案 1 :(得分:0)

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