2009-03-06 5 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") 

По какой-то причине, мой код не работает , Ни один из нежелательных узлов атрибута не удаляется.

В чем проблема? Как удалить узлы атрибутов, значения атрибутов которых не соответствуют числу в моем массиве строк?

Заранее спасибо.

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); 
Смежные вопросы