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

  • 相关阅读:
    2822 爱在心中
    P1707 刷题比赛
    1269 匈牙利游戏
    1482 路线统计
    Codevs 1287 矩阵乘法&&Noi.cn 09:矩阵乘法(矩阵乘法练手题)
    P2022 有趣的数
    1087 麦森数
    P1111 修复公路
    python为在线漫画站点自制非官方API(未完待续)
    逻辑运算0==x和x==0具体解释
  • 原文地址:https://www.cnblogs.com/xqf222/p/3306771.html
Copyright © 2020-2023  润新知