2008-12-15 26 views
57

¿Cómo puedo cambiar un atributo de un elemento en un archivo XML, usando C#?Cómo cambiar el atributo XML

+0

¿Por qué se votó abajo? O.o – TraumaPony

+1

No tengo ni idea :-), –

+4

En pocas palabras: por favor envíe el código. –

Respuesta

56

mediante LINQ to XML si está utilizando 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

Esta es una muy buena – Graviton

+0

¡Una muy buena de hecho! justo lo que necesitaba, Si necesita buscar ciertos atributos del libro, simplemente agregue. Donde (c => (cadena) c.Atribuya ("myattribute") == "algún valor") antes de seleccionar c; – VisualBean

+0

No tiene sentido escribir 'from c in blah select c'. – SLaks

62

Mike; Cada vez que tengo que modificar un documento XML que trabajo de esta manera:

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

espero que les sea útil

11

Si el atributo que desea cambiar no existe o se ha eliminado accidentalmente, a continuación, una excepción ocurre. Le sugiero que primero se crea un nuevo atributo y los envía a la función como la siguiente:

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); 
      } 
     } 
    } 

Uso:

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

Ese es un buen punto. Nunca supongas que ese atributo está ahí. –

Cuestiones relacionadas