xml文件中thebook.ChildNodes.Count会随着thebook.ChildNodes.Item(i)的使用自动的减少
解决方法是给记录初值
thebook1 = xml.CreateElement("book1");
int m = thebook.ChildNodes.Count;
for (int i = 0; i < m; i++)
{
thebook1.AppendChild(thebook.ChildNodes.Item(0));
}
thebook.AppendChild(thebook1);
这样就把原本的xml文件里面的
<book category="CHILDREN">
<title>huluwa</title>
<author> </author>
<year> </year>
<price>30</price>
</book>
给添加了book1的子节点,成为
<book category="CHILDREN">
<book1>
<title>huluwa</title>
<author> </author>
<year> </year>
<price>30</price>
</book1>
</book>
好了代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace xml实验2
{
class Program
{
static void Main(string[] args)
{
XmlDocument xml = new XmlDocument();
XmlElement thebook = null, thebook1 = null, thelement = null ;
xml.Load("Bookstore.xml");
XmlElement root = xml.DocumentElement;
thebook =(XmlElement)root.SelectSingleNode("/bookstore/book[@category='CHILDREN']");//获得属性category='CHILDREN' 的节点位置 属性需要加@ 元素不要加
thebook1 = xml.CreateElement("book1");
int m = thebook.ChildNodes.Count;
for (int i = 0; i < m; i++)
{
thebook1.AppendChild(thebook.ChildNodes.Item(0));
}
thebook.AppendChild(thebook1);
thebook1 = xml.CreateElement("book1");//添加新元素title、author、year、price到book1
thelement = xml.CreateElement("title");
thelement.InnerText = "huluwa";
thebook1.AppendChild(thelement);
thelement = xml.CreateElement("author");
thelement.InnerText = " ";
thebook1.AppendChild(thelement);
thelement = xml.CreateElement("year");
thelement.InnerText = " ";
thebook1.AppendChild(thelement);
thelement = xml.CreateElement("price");
thelement.InnerText = "30";
thebook1.AppendChild(thelement);
thebook.AppendChild(thebook1);
XmlNodeList someBook = root.SelectNodes("/bookstore/book/book1[price<30]");//删除子节点价格低于30的书
for (int j = 0; j < someBook.Count; j++)
someBook.Item(j).ParentNode.RemoveChild(someBook.Item(j));
XmlNodeList someBooks = root.SelectNodes("/bookstore/book[price<30]");
for (int i = 0; i < someBooks.Count; i++)
{
someBooks.Item(i).ParentNode.RemoveChild(someBooks.Item(i));
}
xml.Save("Bookstore.xml");//记得保存 可以用xml.outerxml查看Console.WriteLine(theBook.OuterXml);
}
}
}