记得向根根节点添加属性可以用以下代码:
XmlDocument xmldoc = new XmlDocument();
XmlElement root = xmldoc.DocumentElement;
root.SetAttribute("newattr","attrvalue");
好象以上这个是个特例一样。如果要向[已存在的]子节点添加属性,似乎必须得用以下这种替换节点的方法:
XmlNode currNode = xmldoc.SelectNodes("//item")[1];//先用XPath定位目标
XmlElement newElem = xmldoc.CreateElement("item"); //然后建立新元素
...//接着重设元素文本值
newElem.SetAttribute("newattr","attrvalue");//同时添加属性和属性值
root.ReplaceChild(newElem,currNode);偶在MSDN找了半天,似乎没有他法。请问有没有更直接的方法?

解决方案 »

  1.   

    为什么要替换?XmlElement newElem = xmldoc.SelectNodes("//item") as XmlElement;
    newElem.SetAttribute("newattr","attrvalue");结束
      

  2.   

    XmlNode.Attribuates.Append( 新属性 )
      

  3.   

    TO aiyagaze() :第一行就没编译通过TO hdt(倦怠):在MSDN上没有找到以上用法能给点示例吗?
      

  4.   

    using System;
    using System.IO;
    using System.Xml;public class Sample {  public static void Main() {    XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "</book>");    XmlNode root = doc.FirstChild;    //Create a new attribute.
        string ns = root.GetNamespaceOfPrefix("bk");
        XmlNode attr = doc.CreateNode(XmlNodeType.Attribute, "genre", ns);
        attr.Value = "novel";    //Add the attribute to the document.
        root.Attributes.SetNamedItem(attr);    Console.WriteLine("Display the modified XML...");
        doc.Save(Console.Out);  }
    }
      

  5.   

    using System;
    using System.IO;
    using System.Xml;public class Sample
    {
      public static void Main(){
      
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "</book>");          //Create a new attribute.
        XmlAttribute newAttr = doc.CreateAttribute("genre");
        newAttr.Value = "novel";    //Create an attribute collection and add the new attribute
        //to the collection.
        XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;
        attrColl.Append(newAttr);    Console.WriteLine("Display the modified XML...\r\n");
        Console.WriteLine(doc.OuterXml);  
      }
    }
      

  6.   

    我看错了。
    你select的是nodes
    foreach (XmlElement xmlEle in xmldoc.SelectNodes("//item"))
    {
         xmlEle.SetAttribute("a", "b");
    }
      

  7.   

    TO aiyagaze() :不用foreach,只给一个节点添加属性怎么写?