Het XML-kenmerk wijzigen

Hoe kan ik een attribuut van een element in een XML-bestand wijzigen met C#?


Antwoord 1, autoriteit 100%

Mike;
Elke keer dat ik een XML-document moet wijzigen, werk ik het op deze manier:

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

Ik hoop dat je het nuttig vindt


Antwoord 2, autoriteit 86%

Gebruik van LINQ naar xml als je framework 3.5 gebruikt:

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

Antwoord 3, autoriteit 19%

Als het kenmerk dat u wilt wijzigen niet bestaat of per ongeluk is verwijderd, treedt er een uitzondering op. Ik raad u aan eerst een nieuw attribuut aan te maken en dit naar een functie zoals de volgende te sturen:

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

Gebruik:

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

Antwoord 4, autoriteit 3%

Hier is het begin van een parserklasse om u op weg te helpen. Dit werd uiteindelijk mijn oplossing voor een soortgelijk probleem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML
{
    public class Parser
    {
        private string _FilePath = string.Empty;
        private XDocument _XML_Doc = null;
        public Parser(string filePath)
        {
            _FilePath = filePath;
            _XML_Doc = XDocument.Load(_FilePath);
        }
        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string attributeName, string newValue)
        {
            ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
        }
        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
        }
        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) and value (oldValue)  
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);              
        }
        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), 
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// If oldValues is empty then oldValues will be ignored.
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValues"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
        {
            List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
            foreach (XElement element in elements)
            {
                if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
                {
                    if (element.Attribute(attributeName) != null)
                    {
                        if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
                        { element.Attribute(attributeName).Value = newValue; }
                    }
                }
            }
        }
        public void SaveChangesToFile()
        {
            _XML_Doc.Save(_FilePath);
        }
    }
}

Other episodes