2009-03-06 12 views
0

私はまだxmlで遊んでいます。今私はこのようなファイルを持っています:属性に基づいてXElementを削除

<?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 [email protected] = 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([email protected]) 
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) [email protected] = h).Remove() 
Next 
'save the xml 
doc.Save("C:\myXMLFile.xml") 

を、私のコードは動作しません。 。望ましくない属性ノードは削除されません。

問題が何ですか?どのようにid属性の値が文字列配列内の任意の数と一致しない属性ノードを削除できますか?

ありがとうございます。

P.S. - 自分の問題を明確に説明してくれることを願っています。

答えて

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 [email protected] = 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([email protected]) 
End If 
Next 
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); 
関連する問題