记得向根根节点添加属性可以用以下代码:
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找了半天,似乎没有他法。请问有没有更直接的方法?
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找了半天,似乎没有他法。请问有没有更直接的方法?
newElem.SetAttribute("newattr","attrvalue");结束
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); }
}
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);
}
}
你select的是nodes
foreach (XmlElement xmlEle in xmldoc.SelectNodes("//item"))
{
xmlEle.SetAttribute("a", "b");
}