private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"d:\category.xml");
XmlNode book;
XmlNode root = doc.DocumentElement;
book = root.SelectSingleNode("/Category/CategoryNode[@name='kaifa1']");
label1.Text = book.Attributes["value"].Value;
}
private void button2_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"d:\category.xml");
XmlNode book;
XmlNode root = doc.DocumentElement;
book = root.SelectSingleNode("/Category[CategoryNode='8888']");
label1.Text = book.InnerText;
}
private void button3_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"d:\category.xml");
XmlNode root = doc.DocumentElement;
XmlElement element = doc.CreateElement("CategoryNode");
element.InnerText = "123";
root.AppendChild(element);
doc.Save(@"d:\category.xml");
}
Xml文件:
<?xml version="1.0"?>
<Category>
<CategoryNode name="kaifa" value="2.jpg">8888</CategoryNode>
<CategoryNode name="kaifa1" value="21.jpg" />
<CategoryNode name="kaifa2" value="22.jpg" />
<CategoryNode>123</CategoryNode>
</Category>
MSDN 文档
[C#]
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("booksort.xml");
//Create an XmlNamespaceManager for resolving namespaces.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:samples");
//Select the book node with the matching attribute value.
XmlNode book;
XmlElement root = doc.DocumentElement;
book = root.SelectSingleNode("descendant::book[@bk:ISBN='1-861001-57-6']", nsmgr);
Console.WriteLine(book.OuterXml);
}
}
<?xml version="1.0"?>
<!-- A fragment of a book store inventory database -->
<bookstore xmlns:bk="urn:samples">
<book genre="novel" publicationdate="1997" bk:ISBN="1-861001-57-8">
<title>Pride And Prejudice</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>24.95</price>
</book>
<book genre="novel" publicationdate="1992" bk:ISBN="1-861002-30-1">
<title>The Handmaid's Tale</title>
<author>
<first-name>Margaret</first-name>
<last-name>Atwood</last-name>
</author>
<price>29.95</price>
</book>
<book genre="novel" publicationdate="1991" bk:ISBN="1-861001-57-6">
<title>Emma</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
<book genre="novel" publicationdate="1982" bk:ISBN="1-861001-45-3">
<title>Sense and Sensibility</title>
<author>
<first-name>Jane</first-name>
<last-name>Austen</last-name>
</author>
<price>19.95</price>
</book>
</bookstore>
Xml中SelectSingleNode方法中的xpath用法
最常见的XML数据类型有:Element, Attribute,Comment, Text.
Element, 指形如<Name>Tom<Name>的节点。它可以包括:Element, Text, Comment, ProcessingInstruction, CDATA, and EntityReference.
Attribute, 指在<Employee id=”12345”>中的粗体部分。
Comment,指形如:<!-- my comment --> 的节点。
Text,指在<Name>Tom<Name>的粗体部分。
在XML中,可以用XmlNode对象来参照各种XML数据类型。
2.1 查询已知绝对路径的节点(集)
objNodeList = objDoc.SelectNodes(“Company/Department/Employees/Employee”)
或者
objNodeList = objNode.SelectNodes(“/Company/Department/Employees/Employee”)
以上两种方法可返回一个NodeList对象,如果要返回单个节点可使用SelectSingleNode方法,该方法如果查询到一个或多个节点,返回第一个节点;如果没有查询的任何节点返回 Nothing。例如:
objNode = objNode.SelectSingleNode(“/Company/Department/Employees/Employee”)
If Not (objNode is Nothing) then
‘- Do process
End If
2.2 查询已知相对路径的节点(集)
可使用类似于文件路径的相对路径的方式来查询XML的数据
objNode = objDoc.SelectSingleNode(“Company/Department”)
objNodeList = objNode.SelectNodes(“../Department)
objNode = objNode.SelectNode(“Employees/Employee”)
2.3 查询已知元素名的节点(集)
在使用不规则的层次文档时,由于不知道中间层次的元素名,可使用//符号来越过中间的节点,查询其子,孙或多层次下的其他所有元素。例如:
objNodeList = objDoc.SelectNodes(“Company//Employee”)
2.4 查询属性(attribute)节点
以上的各种方法都返回元素(element)节点(集),返回属性(attribute),只需要采用相应的方法,在属性名前加一个@符号即可,例如:
objNodeList = objDoc.SelectNodes(“Company/Department/Employees/Employee/@id”)
objNodeList = objDoc.SelectNodes(“Company//@id”)
2.5 查询Text节点
使用text()来获取Text节点。
objNode = objDoc.SelectSingleNode(“Company/Department/Deparmt_Name/text()”)
2.6 查询特定条件的节点
使用[]符号来查询特定条件的节点。例如:
a. 返回id号为 10102的Employee节点
objNode = objDoc.SelectSingleNode(“Company/Department/Employees/Employee[@id=’10102’]”)
b. 返回Name为Zhang Qi的Name 节点
objNode = objDoc.SelectSingleNode(“Company/Department/Employees/Employee/Name[text()=’Zhang Qi’]”)
c. 返回部门含有职员22345的部门名称节点
objNode = objDoc.SelectSingleNode("Company/Department[Employees/Employee/@id='22345']/Department_Name")
2.7 查询多重模式的节点
使用 | 符号可以获得多重模式的节点。例如:
objNodeList = objDoc.SelectNodes(“Company/Department/Department_Name | Company/Department/Manager”)
2.8 查询任意子节点
使用*符号可以返回当前节点的所有子节点。
objNodeList = objDoc.SelectNodes(“Company/*/Manager)
或者
objNodeList = objNode.ChildNodes
3 XML数据的编辑
3.1 增加一个元素的属性(attribute)节点
Dim objNodeAttr As XmlNode
objNodeAttr = objDoc.CreateAttribute("id", Nothing)
objNodeAttr.InnerXml = "101"
objNode.Attributes.Append(objNodeAttr)
3.2 删除一个元素的属性
objNode.Attributes.Remove(objNodeAttr)
3.3 增加一个子元素(Element)
Dim objNodeChild As XmlNode
objNodeChild = objDoc.CreateElement(Nothing, "ID", Nothing)
objNodeChild.InnerXml = "101"
objNode.AppendChild(objNodeChild)
3.4 删除一个子元素
objNode.RemoveChild(objNodeChild)
3.5 替换一个子元素
objNOde.ReplaceChild(newChild,oldChild)
4 参考数据
<?xml version="1.0" encoding="UTF-8"?>
<Company>
<Department id="101">
<Department_Name>Cai WuBu</Department_Name>
<Manager>Zhang Bin</Manager>
<Employees>
<Employee id="12345">
<Employee_ID>12345</Employee_ID>
<Name>Zhang Bin</Name>
<Gender>male</Gender>
</Employee>
<Employee id="10101">
<Employee_ID>10101</Employee_ID>
<Name>Zhang QI</Name>
<Gender>female</Gender>
</Employee>
<Employee id="10102">
<Employee_ID>10102</Employee_ID>
<Name>Zhang Xia</Name>
<Gender>male</Gender>
</Employee>
<Employee id="10201">
<Employee_ID>10201</Employee_ID>
<Name>ZhangChuang</Name>
<Gender>male</Gender>
</Employee>
<Employee id="10202">
<Employee_ID>10202</Employee_ID>
<Name>Zhang Jun</Name>
<Gender>male</Gender>
</Employee>
</Employees>
</Department>
<Department id="102">
<Department_Name>KaiFa Bu</Department_Name>
<Manager>Wang Bin</Manager>
<Employees>
<Employee id="22345">
<Employee_ID>22345</Employee_ID>
<Name>Wang Bin</Name>
<Gender>male</Gender>
</Employee>
<Employee id="20101">
<Employee_ID>20101</Employee_ID>
<Name>Wang QI</Name>
<Gender>female</Gender>
</Employee>
<Employee id="20102">
<Employee_ID>20102</Employee_ID>
<Name>Wang Xia</Name>
<Gender>male</Gender>
</Employee>
<Employee id="20201">
<Employee_ID>20201</Employee_ID>
<Name>Wang Chuang</Name>
<Gender>male</Gender>
</Employee>
<Employee id="20202">
<Employee_ID>20201</Employee_ID>
<Name>Wang Jun</Name>
<Gender>male</Gender>
</Employee>
</Employees>
</Department>
</Company>
XML操作类 XmlOp.cs
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using System.IO;
11//引用命名空间
12using System.Xml;
13//51aspx.c_o_m
14
15namespace xmlOp
16{
17 /// <summary>
18 /// xmlOp 类提供对XML文件的读/写/查询/更新/添加/删除 等操作!
19 /// </summary>
20 public class XmlOp
21 {
22 //声明一个XmlDocument空对象
23 protected XmlDocument doc = new XmlDocument();
24 public XmlOp(string xmlFile)
25 {
26 doc.Load(GetXmlFilePath(xmlFile));//载入Xml文档
27 }
28 //保存文件
29 public void Save(string filePath)
30 {
31 doc.Save(GetXmlFilePath(filePath));
32 }
33 //属性查询,返回属性值
34 public string SelectAttrib(string XmlPathNode, string Attrib)
35 {
36 string _strNode = "";
37 _strNode = doc.SelectSingleNode(XmlPathNode).Attributes[Attrib].Value;
38 return _strNode;
39 }
40 // 添加属性
41 public bool InsertAttrib(string MainNode, string Attrib, string AttribContent)
42 {
43 try
44 {
45 XmlElement objNode = (XmlElement)doc.SelectSingleNode(MainNode); //强制转化成XmlElement对象
46 objNode.SetAttribute(Attrib, AttribContent); //XmlElement对象添加属性方法
47 return true;
48 }
49 catch
50 {
51 return false;
52 }
53 }
54 //节点值查询与判断
55 public bool SelectNode(string XmlPathNode, int index, string NodeText)
56 {
57 XmlNodeList _NodeList = doc.SelectNodes(XmlPathNode);
58 //循环遍历节点,查询是否存在该节点
59 for (int i = 0; i < _NodeList.Count; i++)
60 {
61 if (_NodeList[i].ChildNodes[index].InnerText == NodeText)
62 {
63 return true;
64 break;
65 }
66 }
67 return false;
68 }
69 //获取子节点个数
70 public int NodeCount(string XmlPathNode)
71 {
72 int i = 0;
73 try
74 {
75 i = doc.SelectSingleNode(XmlPathNode).ChildNodes.Count;
76 }
77 catch
78 {
79 i = 0;
80 }
81 return i;
82 }
83 //插入一个节点,带N个子节点
84 public bool InsertNode(string MainNode, string ChildNode, string[] Element, string[] Content)
85 {
86 try
87 {
88 XmlNode objRootNode = doc.SelectSingleNode(MainNode); //声明XmlNode对象
89 XmlElement objChildNode = doc.CreateElement(ChildNode); //创建XmlElement对象
90 objRootNode.AppendChild(objChildNode);
91 for (int i = 0; i < Element.Length; i++) //循环插入节点元素
92 {
93 XmlElement objElement = doc.CreateElement(Element[i]);
94 objElement.InnerText = Content[i];
95 objChildNode.AppendChild(objElement);
96 }
97 return true;
98 }
99 catch
100 {
101 return false;
102 }
103 }
104 // 根据Xml文件的节点路径,返回一个DataSet数据集
105 public DataSet GetDs(string XmlPathNode)
106 {
107 DataSet ds = new DataSet();
108 try
109 {
110 StringReader read = new StringReader(doc.SelectSingleNode(XmlPathNode).OuterXml);
111 ds.ReadXml(read); //利用DataSet的ReadXml方法读取StringReader文件流
112 read.Close();
113 }
114 catch
115 { }
116 return ds;
117 }
118 // 返回Xml文件实际路径
119 public string GetXmlFilePath(string xmlFile)
120 {
121 return xmlFile;
122 }
123 }
124}
1using System;
2using System.Data;
3using System.Configuration;
4using System.Web;
5using System.Web.Security;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using System.Web.UI.WebControls.WebParts;
9using System.Web.UI.HtmlControls;
10using System.IO;
11//引用命名空间
12using System.Xml;
13//51aspx.c_o_m
14
15namespace xmlOp
16{
17 /// <summary>
18 /// xmlOp 类提供对XML文件的读/写/查询/更新/添加/删除 等操作!
19 /// </summary>
20 public class XmlOp
21 {
22 //声明一个XmlDocument空对象
23 protected XmlDocument doc = new XmlDocument();
24 public XmlOp(string xmlFile)
25 {
26 doc.Load(GetXmlFilePath(xmlFile));//载入Xml文档
27 }
28 //保存文件
29 public void Save(string filePath)
30 {
31 doc.Save(GetXmlFilePath(filePath));
32 }
33 //属性查询,返回属性值
34 public string SelectAttrib(string XmlPathNode, string Attrib)
35 {
36 string _strNode = "";
37 _strNode = doc.SelectSingleNode(XmlPathNode).Attributes[Attrib].Value;
38 return _strNode;
39 }
40 // 添加属性
41 public bool InsertAttrib(string MainNode, string Attrib, string AttribContent)
42 {
43 try
44 {
45 XmlElement objNode = (XmlElement)doc.SelectSingleNode(MainNode); //强制转化成XmlElement对象
46 objNode.SetAttribute(Attrib, AttribContent); //XmlElement对象添加属性方法
47 return true;
48 }
49 catch
50 {
51 return false;
52 }
53 }
54 //节点值查询与判断
55 public bool SelectNode(string XmlPathNode, int index, string NodeText)
56 {
57 XmlNodeList _NodeList = doc.SelectNodes(XmlPathNode);
58 //循环遍历节点,查询是否存在该节点
59 for (int i = 0; i < _NodeList.Count; i++)
60 {
61 if (_NodeList[i].ChildNodes[index].InnerText == NodeText)
62 {
63 return true;
64 break;
65 }
66 }
67 return false;
68 }
69 //获取子节点个数
70 public int NodeCount(string XmlPathNode)
71 {
72 int i = 0;
73 try
74 {
75 i = doc.SelectSingleNode(XmlPathNode).ChildNodes.Count;
76 }
77 catch
78 {
79 i = 0;
80 }
81 return i;
82 }
83 //插入一个节点,带N个子节点
84 public bool InsertNode(string MainNode, string ChildNode, string[] Element, string[] Content)
85 {
86 try
87 {
88 XmlNode objRootNode = doc.SelectSingleNode(MainNode); //声明XmlNode对象
89 XmlElement objChildNode = doc.CreateElement(ChildNode); //创建XmlElement对象
90 objRootNode.AppendChild(objChildNode);
91 for (int i = 0; i < Element.Length; i++) //循环插入节点元素
92 {
93 XmlElement objElement = doc.CreateElement(Element[i]);
94 objElement.InnerText = Content[i];
95 objChildNode.AppendChild(objElement);
96 }
97 return true;
98 }
99 catch
100 {
101 return false;
102 }
103 }
104 // 根据Xml文件的节点路径,返回一个DataSet数据集
105 public DataSet GetDs(string XmlPathNode)
106 {
107 DataSet ds = new DataSet();
108 try
109 {
110 StringReader read = new StringReader(doc.SelectSingleNode(XmlPathNode).OuterXml);
111 ds.ReadXml(read); //利用DataSet的ReadXml方法读取StringReader文件流
112 read.Close();
113 }
114 catch
115 { }
116 return ds;
117 }
118 // 返回Xml文件实际路径
119 public string GetXmlFilePath(string xmlFile)
120 {
121 return xmlFile;
122 }
123 }
124}