0

我还在玩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 属性指定值的 Attribute 节点。我已经建立了一个包含大约 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 属性值与字符串数组中的任何数字都不匹配的 Attribute 节点?

提前致谢。

PS - 我希望我在描述我的问题时说清楚了。

4

2 回答 2

0

没关系。我想到了。这是我所做的:

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
于 2009-03-06T23:05:13.947 回答
0

删除所有不需要的节点:

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);
于 2012-04-27T06:27:29.083 回答