Xml 基于属性删除元素

Xml 基于属性删除元素,xml,linq-to-xml,xelement,Xml,Linq To Xml,Xelement,我还在玩xml。现在,我有一个如下所示的文件: <?xml version="1.0" encoding="utf-8"?> <Attributes> <AttributeSet id="10110"> <Attribute id="1">some text here</Attribute> <Attribute id="2">some text here</Attribute> <!-- 2

我还在玩xml。现在,我有一个如下所示的文件:

<?xml version="1.0" encoding="utf-8"?>
<Attributes>
 <AttributeSet id="10110">
  <Attribute id="1">some text here</Attribute>
  <Attribute id="2">some text here</Attribute>
  <!-- 298 more Attribute nodes follow -->
  <!-- note that the value for the id attribute is numbered consecutively -->
 </AttributeSet>
</Attributes>
总共有300个属性节点,其中大部分我不需要。我要做的是删除所有没有为id属性指定值的属性节点。我已经建立了一个大约有10个值的字符串数组。这些值表示我希望保留在xml中的属性。剩下的我想去掉

我试图用下面的代码修改xml,方法是删除我不想使用的所有属性节点:

Dim ss() As String = New String() {"39", "41", "38", "111", "148", "222", "256", "270", "283", "284"} 'keep the Attributes whose id value is one of these numbers
Dim rv As New List(Of String)'will hold Attribute ids to remove
Dim bool As Boolean = False
For Each x As XElement In doc...<eb:Attribute>
 For Each s As String In ss
  If x.@id = s Then
   bool = True
   Exit For
  End If
 Next
 If bool = True Then
  'do nothing
 Else 'no attribute matched any of the attribute ids listed mark xelement for removal
  rv.Add(x.@id)
 End If
Next
'now remove the xelement
For Each tr As String In rv
 Dim h As String = tr
 doc...<eb:Attribute>.Where(Function(g) g.@id = h).Remove()
Next
'save the xml
doc.Save("C:\myXMLFile.xml")
由于某种原因,我的代码不起作用。不会删除任何不需要的属性节点

有什么问题吗?如何删除id属性值与字符串数组中的任何数字都不匹配的属性节点

提前谢谢


我希望我在描述我的问题时能说清楚。

没关系。我想出来了。以下是我所做的:

For Each x As XElement In doc...<eb:Attribute>
 **bool = False 'I simply added this line of code and everything worked perfectly**
 For Each s As String In ss
  If x.@id = s Then
   bool = True
   Exit For
  End If
 Next
 If bool = True Then
  'do nothing
 Else 'no attribute matched any of the attribute ids listed so remove the xelement
  rv.Add(x.@id)
 End If
Next
删除所有不需要的节点:

XDocument xDoc = XDocument.Load(xmlFilename);

List<string> keepList = new List<string> { "1", "2", "3" };

var unwanted = from element in xDoc.Elements("Attributes").Elements("AttributeSet").Elements("Attribute")
               where !keepList.Contains((string)element.Attribute("id"))
               select element;

unwanted.Remove();

xDoc.Save(xmlFilename);