2008-12-15 6 views
57

Comment puis-je modifier un attribut d'un élément dans un fichier XML en utilisant C#?Comment modifier l'attribut XML

+0

Pourquoi cette voté vers le bas? O.o – TraumaPony

+1

Je n'ai aucune idée :-), –

+4

Pour le mettre succintly: plz envoyer le codez. –

Répondre

56

LINQ to XML si vous utilisez Framework 3.5:

using System.Xml.Linq; 

XDocument xmlFile = XDocument.Load("books.xml"); 

var query = from c in xmlFile.Elements("catalog").Elements("book")  
      select c; 

foreach (XElement book in query) 
{ 
    book.Attribute("attr1").Value = "MyNewValue"; 
} 

xmlFile.Save("books.xml"); 
+1

C'est un bon – Graviton

+0

Vraiment un bon! juste ce dont j'avais besoin, Si vous avez besoin de rechercher certains attributs de livre, ajoutez simplement .Where (c => (chaîne) c.Attribute ("myattribute") == "valeur") avant de sélectionner c; – VisualBean

+0

Il ne sert à rien d'écrire 'de c dans blah select c'. – SLaks

62

Mike; Chaque fois que je dois modifier un document XML Je travaille cette façon:

//Here is the variable with which you assign a new value to the attribute 
string newValue = string.Empty; 
XmlDocument xmlDoc = new XmlDocument(); 

xmlDoc.Load(xmlFile); 

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element"); 
node.Attributes[0].Value = newValue; 

xmlDoc.Save(xmlFile); 

//xmlFile is the path of your file to be modified 

J'espère que vous trouverez utile

11

Si l'attribut que vous souhaitez modifier n'existe pas ou a été accidentellement retiré, puis une exception se produit. Je vous suggère d'abord créer un nouvel attribut et l'envoyer à une fonction comme ce qui suit:

private void SetAttrSafe(XmlNode node,params XmlAttribute[] attrList) 
    { 
     foreach (var attr in attrList) 
     { 
      if (node.Attributes[attr.Name] != null) 
      { 
       node.Attributes[attr.Name].Value = attr.Value; 
      } 
      else 
      { 
       node.Attributes.Append(attr); 
      } 
     } 
    } 

Utilisation:

XmlAttribute attr = dom.CreateAttribute("name"); 
    attr.Value = value; 
    SetAttrSafe(node, attr); 
+0

C'est un bon point. Ne supposez jamais que cet attribut est là. –

Questions connexes