如何追加XML節點

david0620 2009-01-21 01:51:05
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<PN>00000001</PN>
<Image>test1</Image>
<Time>2009/1/21 下午 01:42:43</Time>
</book>
</bookstore>

如何在XML檔上追加一個<book>節點,完成後像下面這樣?
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<PN>00000001</PN>
<Image>test1</Image>
<Time>2009/1/21 下午 01:42:43</Time>
</book>
<book genre="fantasy" ISBN="2-3631-4">
<PN>00000002</PN>
<Image>test2</Image>
<Time>2009/1/21 下午 01:42:43</Time>
</book>
</bookstore>
...全文
127 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
j45kp 2009-01-21
  • 打赏
  • 举报
回复

<Expressions>

<Expression ID="1" name="a+b" remark="测试一">
<Param name="a" remark="注解1"></Param>
<Param name="b" remark="注解2"></Param>
</Expression>

</Expressions>

如何操作使该文件内容变成:
<?xml version="1.0" encoding="utf-8" ?>

<Expressions>

<Expression ID="1" name="a+b" remark="测试一">
<Param name="a" remark="注解1"></Param>
<Param name="b" remark="注解2"></Param>
</Expression>
<Expression ID="2" name="x-y" remark="测试二">
<Param name="x" remark="注解1"></Param>
<Param name="y" remark="注解2"></Param>
</Expression>


</Expressions>
//------------------------------
string sFileName = "ExpXml.xml";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sFileName);
XmlNode node = xmldoc.DocumentElement.ChildNodes[0].CloneNode(true);
node.Attributes["ID"].Value = "2";
node.Attributes["name"].Value = "x-y";
node["Param"].Attributes["name"].Value = "x";
node["Param"].InnerText="aaaa";
//......
xmldoc.DocumentElement.AppendChild(node);
xmldoc.Save(sFileName);
wangping_li 2009-01-21
  • 打赏
  • 举报
回复

XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("XML文件名"); //加载你的XML文件
XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找bookstore
XmlElement xebook=xmlDoc.CreateElement("book");//创建book节点
xebook.SetAttribute("genre","fantasy");//设置book节点的genre属性
xebook.SetAttribute("ISBN","2-3631-4");//设置book节点的ISBN属性
XmlElement xesub1=xmlDoc.CreateElement("PN"); //创建PN节点
xesub1.InnerText="00000002";//为PN节点赋值
xebook.AppendChild(xesub1);//添加到book节点下
XmlElement xesub2=xmlDoc.CreateElement("Image");//创建Image节点
xesub2.InnerText="test2";//为Image节点赋值
xebook.AppendChild(xesub2); //添加到book节点下
XmlElement xesub3=xmlDoc.CreateElement("Time");//创建Time节点
xesub3.InnerText="2009/1/21 下午 01:42:43";//为Time节点赋值
xebook.AppendChild(xesub3);//添加到book节点下
root.AppendChild(xebook);//将book节点添加到bookstore节点下
xmlDoc.Save("你的XML文件名"); //保存XML文件
bennyyyyy 2009-01-21
  • 打赏
  • 举报
回复
调用父节点的appendchild方法
jinjazz 2009-01-21
  • 打赏
  • 举报
回复
类似

doc.ChildNodes[0].AppendChild();
Ephesus 2009-01-21
  • 打赏
  • 举报
回复
XmlNode当中有AppendChild方法,用它可以在你要插入的节点中插入你的东西

111,130

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧