属性に基づいてXElementを削除します
-
05-07-2019 - |
質問
まだ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属性値が文字列配列のどの番号とも一致しない属性ノードを削除するにはどうすればよいですか?
事前に感謝します。
PS -私は自分の問題を説明することで自分自身を明確にしたいと思います。
解決
気にしないで。私はそれを考え出した。ここで私がしたこと:
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);
所属していません StackOverflow