C#操作XML
2020-12-13 14:21
标签:des style blog io color ar for sp 文件 c# XML 创建XMl C# 创建的XML C#操作XML 标签:des style blog io color ar for sp 文件 原文地址:http://www.cnblogs.com/kongsq/p/3870896.html 1 XmlDocument doc = new XmlDocument();
2 //加载xml文件
3 doc.Load("order.xml");
4
5 //根节点
6 XmlElement root = doc.DocumentElement;
7
8 XmlNodeList xnl = root.ChildNodes;
9
10 //
11 //读取标签的名字
12 Console.WriteLine(xnl[0].Name);
13
14 Console.WriteLine(xnl[0].InnerText);
15 Console.WriteLine(xnl[1].InnerText);
16
17 XmlNode items = xnl[2];
18
19 //orderitem
20 XmlNodeList xnl1 = items.ChildNodes;
21
22 foreach (XmlNode node in xnl1)
23 {
24 //获取属性的值
25 Console.WriteLine(node.Attributes["Name"].Value);
26 Console.WriteLine(node.Attributes["Count"].Value);
27 }
1 xml version="1.0" encoding="utf-8"?>
2 Order>
3 OrderNo>tj000001OrderNo>
4 CustomerName>微微CustomerName>
5 Items>
6 OrderItem Name="媳妇" Count="10" />
7 OrderItem Name="房子" Count="10" />
8 Items>
9 Order>
XmlDocument doc = new XmlDocument();
//加载xml文件
doc.Load("books.xml");
//根节点
XmlElement books = doc.DocumentElement;
//books 下的所有book元素
XmlNodeList xnl = books.ChildNodes;
foreach (XmlNode node in xnl)
{
Console.WriteLine(node.ChildNodes[0].InnerText);
Console.WriteLine(node.ChildNodes[1].InnerText);
}
xml version="1.0" encoding="utf-8"?>
Books>
Book>
Name><b>123</b>Name>
Price>10Price>
Book>
Book>
Name>12梅2Name>
Price>20Price>
Book>
Book>
Name>c#图解教程Name>
Price>30Price>
Book>
Book>
Name>XX梅2Name>
Price>20Price>
Book>
Books>
1 //内存中创建一个xml
2 XmlDocument doc = new XmlDocument();
3 //
4 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
5 doc.AppendChild(dec);
6
7 //根节点 Order
8 XmlElement order = doc.CreateElement("Order");
9 doc.AppendChild(order);
10 //
11 XmlElement customerName = doc.CreateElement("CustomerName");
12 customerName.InnerText = "微微";
13 //
14 order.AppendChild(customerName);
15 //
16 XmlElement orderNo = doc.CreateElement("OrderNo");
17 orderNo.InnerText = "tj000001";
18 //
19 order.AppendChild(orderNo);
20 //
21 XmlElement items = doc.CreateElement("Items");
22 order.AppendChild(items);
23
24
25 //
26 XmlElement orderItem1 = doc.CreateElement("OrderItem");
27 orderItem1.SetAttribute("Name", "媳妇");
28 orderItem1.SetAttribute("Count","10");
29 items.AppendChild(orderItem1);
30
31 //
32 XmlElement orderItem2 = doc.CreateElement("OrderItem");
33 orderItem2.SetAttribute("Name","房子");
34 orderItem2.SetAttribute("Count","10");
35 items.AppendChild(orderItem2);
36
37 //保存到文件
38 doc.Save("order.xml");
xml version="1.0" encoding="utf-8"?>
Order>
CustomerName>微微CustomerName>
OrderNo>tj000001OrderNo>
Items>
OrderItem Name="媳妇" Count="10" />
OrderItem Name="房子" Count="10" />
Items>
Order>