Domanda

Sto ancora giocando con XML. Ora ho un file che assomiglia a questo:

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

Esistono in totale 300 nodi di attributi, molti dei quali non mi servono. Quello che vorrei fare è rimuovere tutti i nodi Attribute che non hanno un valore specificato per l'attributo id. Ho stabilito un array di stringhe con circa 10 valori. Questi valori rappresentano gli attributi che vorrei mantenere nel file XML. Il resto mi piacerebbe rimuovere.

Quello che sto cercando di fare con il codice seguente è modificare l'xml rimuovendo tutti i nodi Attribute che non voglio usare:

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")

Per qualche ragione, il mio codice non funziona. Nessuno dei nodi di attributi indesiderati viene rimosso.

Qual è il problema? Come posso rimuovere i nodi di attributo i cui valori di attributo id non corrispondono a nessun numero nel mio array di stringhe?

Grazie in anticipo.

P.S. - Spero di essermi chiarito nel descrivere il mio problema.

È stato utile?

Soluzione

Non importa. L'avevo capito. Ecco cosa ho fatto:

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

Altri suggerimenti

Rimuovi tutti i nodi indesiderati:

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top