C#给XmlNode节点添加Name属性

 准备生成的XML文件格式如下:

<?xml version="1.0" encoding="utf-8" ?>
<Update>
  <Soft Name="BlogWriter">
    <Verson>1.0.1.2</Verson>
    <DownLoad>http://www.csdn.net/BlogWrite.rar</DownLoad>
  </Soft>
</Update>

详细代码为:

            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.AppendChild(dec);
            //创建一个根节点(一级)
            XmlElement root = doc.CreateElement("Update");
            doc.AppendChild(root);
            //创建节点(二级)
            XmlNode node = doc.CreateElement("Soft");
            node.Attributes.Append(CreateAttribute(node, "Name", "BlogWriter"));
            //创建节点(三级)
            XmlElement element1 = doc.CreateElement("Verson");
            element1.InnerText = "1.0.1.2";
            node.AppendChild(element1);

            XmlElement element2 = doc.CreateElement("DownLoad");
            element2.InnerText = "http://www.csdn.net/BlogWrite.rar";
            node.AppendChild(element2);

            root.AppendChild(node);
            doc.Save(@"C:\web\bb.xml");
            Console.Write(doc.OuterXml);

添加节点属性方法

       public XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
        {
            try
            {
                XmlDocument doc = node.OwnerDocument;
                XmlAttribute attr = null;
                attr = doc.CreateAttribute(attributeName);
                attr.Value = value;
                node.Attributes.SetNamedItem(attr);
                return attr;
            }
            catch (Exception err)
            {
                string desc = err.Message;
                return null;
            }
        } 

需要添加的命名空间为using System.Xml;

原文地址:https://www.cnblogs.com/xqf222/p/3306771.html