如何更改 XML 属性

Posted

技术标签:

【中文标题】如何更改 XML 属性【英文标题】:How to change XML Attribute 【发布时间】:2010-09-26 22:23:51 【问题描述】:

如何使用 C# 更改 XML 文件中元素的属性?

【问题讨论】:

developer.com/net/csharp/article.php/3489611 简而言之:请发送代码。 【参考方案1】:

如果您使用的是框架 3.5,则使用 LINQ to xml:

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

【讨论】:

非常好的一个事实!正是我所需要的,如果您需要搜索某些书籍属性,只需在 select c 之前附加 .Where(c => (string)c.Attribute("myattribute") == "some value");【参考方案2】:

迈克; 每次我需要修改 XML 文档时,我都会这样处理:

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

希望对你有用

【讨论】:

【参考方案3】:

如果您要更改的属性不存在或已被意外删除,则会发生异常。我建议您首先创建一个新属性并将其发送到如下函数:

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

用法:

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

【讨论】:

【参考方案4】:

这是一个解析器类的开始,可以帮助您入门。这最终成为我对类似问题的解决方案:

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

    

【讨论】:

以上是关于如何更改 XML 属性的主要内容,如果未能解决你的问题,请参考以下文章

Xml Jaxb 命名空间和属性顺序

更改XML属性的值会删除其他属性

在转换为 XML 之前更改 JSON 对象中的属性名称

在不更改属性顺序的情况下获取 XML

从 xmlDocument 中选择特定的 xml 节点,然后更改 xml 节点的属性

如何在 MessageContract 类型中使用 XML 属性?