Pregunta

Todavía estoy jugando con xml. Ahora tengo un archivo que se ve así:

<?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>

Hay un total de 300 nodos de atributos, la mayoría de los cuales no necesito. Lo que me gustaría hacer es eliminar todos los nodos de Atributo que no tienen un valor especificado para el atributo id. He establecido una matriz de cadenas con aproximadamente 10 valores. Estos valores representan los atributos que me gustaría mantener en el xml. El resto me gustaría eliminarlo.

Lo que estoy tratando de hacer con el siguiente código es modificar el xml eliminando todos los nodos de atributos que no quiero 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 alguna razón, mi código no funciona. Ninguno de los nodos de atributos no deseados se eliminan.

¿Cuál es el problema? ¿Cómo puedo eliminar los nodos de atributo cuyos valores de atributo de identificación no coinciden con ningún número en mi matriz de cadenas?

Gracias de antemano.

P.S. - Espero haberme dejado claro al describir mi problema.

¿Fue útil?

Solución

No importa. Me lo imaginé. Aquí lo que hice:

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

Otros consejos

Eliminar todos los nodos no deseados:

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top