Question

Je joue toujours avec xml. Maintenant, j'ai un fichier qui ressemble à ceci:

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

Il y a 300 nœuds d'attributs au total, dont la plupart ne sont pas nécessaires. Ce que j'aimerais faire, c'est supprimer tous les nœuds d'attributs qui n'ont pas de valeur spécifiée pour l'attribut id. J'ai établi un tableau de chaînes avec environ 10 valeurs. Ces valeurs représentent les attributs que j'aimerais conserver dans le XML. Je voudrais supprimer le reste.

Ce que j'essaie de faire avec le code ci-dessous, c'est de modifier le XML en supprimant tous les nœuds d'attributs que je ne souhaite pas utiliser:

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

Pour une raison quelconque, mon code ne fonctionne pas. Aucun des nœuds d'attributs indésirables n'est supprimé.

Quel est le problème? Comment puis-je supprimer les nœuds d'attributs dont les valeurs d'attribut id ne correspondent à aucun nombre dans mon tableau de chaînes?

Merci d'avance.

P.S. - J'espère que j'ai bien expliqué mon problème.

Était-ce utile?

La solution

Peu importe. Je l'ai compris. Voici ce que j'ai fait:

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

Autres conseils

Supprimer tous les nœuds indésirables:

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);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top