XElement de exclusão com base no atributo
-
05-07-2019 - |
Pergunta
Eu ainda estou brincando com xml. Agora eu tenho um arquivo que se parece com isso:
<?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>
Há 300 nós de atributo Total, a maioria dos quais eu não preciso. O que eu gostaria de fazer é remover todos os nós de atributo que não têm um valor especificado para o atributo id. Eu estabeleci uma matriz de cadeia com cerca de 10 valores. Estes valores representam os atributos que eu gostaria de manter no xml. O resto eu gostaria de remover.
O que eu estou tentando fazer com o código abaixo é modificar o XML, removendo todos os nós de atributo que não deseja usar:
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")
Por alguma razão, o meu código não funciona. Nenhum dos nós de atributo indesejados são removidos.
Qual é o problema? Como posso remover os nós atributo cujo ID de valores atributo não corresponder a qualquer número na minha matriz de cadeia?
Agradecemos antecipadamente.
P.S. - Espero que eu fiz claro ao descrever o meu problema
.Solução
Nunca mente. Eu percebi isso. Aqui o que eu fiz:
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
Outras dicas
Remover todos os nós indesejáveis:
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);