如何利用C#在XML中添加节点
<?xml version= "1.0 " encoding= "utf-8 "?>
<root>
<person id= "jan " phone= "123456 " />
<person id= "pin " phone= "452369 " />
<person id= "afu " phone= "856932 " />
<person id= "zgmaike " phone= "856321 " />
<age>
<person id= "jan " age= "20 " />
<person id= "pin " age= "26 " />
<person id= "afu " age= "23 " />
</age>
</root>
如何在“ <person id= "afu " age= "23 " /> ”后添加上“ <person id= "zgmaike " age= "25 " /> ”这个节点?
------解决方案--------------------http://www.pconline.com.cn/pcedu/empolder/net/0406/388296.html
------解决方案--------------------public static void AddXmlNode(string xml,string refid,string newid,string age)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xml);
XmlNode refNode = null;
XmlNodeList xnl = xmldoc.SelectNodes( "/root/age/person ");
foreach (XmlNode node in xnl)
{
string attr = node.Attributes[ "id "].Value;
if (attr == refid)//查找节点的id是否等于你输入的id
{
refNode = node;//找到你要的节点
break;
}
}
XmlNode parent = xmldoc.SelectSingleNode( "/root/age ");
XmlElement newNode = xmldoc.CreateElement( "person ");
parent.InsertAfter(newNode,refNode);//在你所选的节点后新增节点
newNode.SetAttribute( "id ",newid);
newNode.SetAttribute( "age ",age);
xmldoc.Save(xml);
}