我还在玩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,删除我不想使用的所有Attribute节点:
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节点?
提前致谢。
P.S。 - 我希望我能够清楚地描述我的问题。
答案 0 :(得分: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
答案 1 :(得分: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);