XmlDocument doc = new XmlDocument();
//加载要读取的XML
doc.Load(@"F:Books.xml");
//获得根节点
XmlElement books = doc.DocumentElement;
//获得子节点 返回节点的集合
XmlNodeList xnl = books.ChildNodes;
foreach (XmlNode item in xnl)
{
XmlElement xe = (XmlElement)item;
Console.WriteLine(xe.GetAttribute("id"));
XmlNodeList nodeList = xe.ChildNodes;
foreach (XmlNode item2 in nodeList)
{
Console.WriteLine(item2.InnerText);
}
}
Console.ReadKey();
修改内容
XmlDocument doc = new XmlDocument();
doc.Load(@"F:Books.xml");
XmlNodeList nodeList = doc.SelectSingleNode("/Books/Book[@id='3d310e87-6c46-4874-859e-c09f3acce589']").ChildNodes;
foreach (XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
//Console.WriteLine(xe.GetAttribute("id"));
if (xe.Name == "Price")
{
Console.WriteLine(xe.InnerText);
xe.InnerText = "oooooooo";
}
}
doc.Save(@"F:Books.xml");
修改属性
//改变属性的值
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
XmlNode xn = doc.SelectSingleNode("/Order/Items/OrderItem[@Name='190']");
xn.Attributes["Count"].Value = "200";
xn.Attributes["Name"].Value = "颜世伟";
doc.Save("Order.xml");
Console.WriteLine("保存成功");