有如下一段XML文件,只取其中的属性:
Code
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1xml version="1.0" encoding="utf-8"?>
2<Root>
3 <Rent>
4 <Item Name="a" Value="1" Test="ly">Item>
5 <Item Name="b" Value="2">Item>
6 <Item Name="c" Value="3">Item>
7 <Item Name="d" Value="4">Item>
8 <Item Name="e" Value="5">Item>
9 Rent>
10 <Sale>
11 <Item Name="aaa" Value="111">Item>
12 <Item Name="bbb" Value="222">Item>
13 <Item Name="ccc" Value="333">Item>
14 <Item Name="ddd" Value="444">Item>
15 <Item Name="eee" Value="555">Item>
16 Sale>
17Root>
18
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1xml version="1.0" encoding="utf-8"?>
2<Root>
3 <Rent>
4 <Item Name="a" Value="1" Test="ly">Item>
5 <Item Name="b" Value="2">Item>
6 <Item Name="c" Value="3">Item>
7 <Item Name="d" Value="4">Item>
8 <Item Name="e" Value="5">Item>
9 Rent>
10 <Sale>
11 <Item Name="aaa" Value="111">Item>
12 <Item Name="bbb" Value="222">Item>
13 <Item Name="ccc" Value="333">Item>
14 <Item Name="ddd" Value="444">Item>
15 <Item Name="eee" Value="555">Item>
16 Sale>
17Root>
18
现在只取 Name 和 Value 值C# 代码如下:
Code
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 XmlDocument xdoc = new XmlDocument();
2 string xmlPath = @"D:\Project\2.xml";
3 xdoc.Load(xmlPath);
4
5 foreach (XmlNode node1 in xdoc.DocumentElement.SelectNodes("./Rent"))
6 {
7
8 foreach (XmlNode item in node1.SelectNodes("./Item"))
9 {
10 foreach (XmlAttribute xma in item.Attributes)
11 {
12
13 string strName = xma.Name;
14
15 string strValue = xma.Value;
16
17 }
18 }
19
20 }
21
22 foreach (XmlNode node2 in xdoc.DocumentElement.SelectNodes("./Sale"))
23 {
24 foreach (XmlNode item in node2.SelectNodes("./Item"))
25 {
26 foreach (XmlAttribute xma in item.Attributes)
27 {
28 string strName = xma.Name;
29 string strValue = xma.Value;
30 }
31 }
32 }
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 XmlDocument xdoc = new XmlDocument();
2 string xmlPath = @"D:\Project\2.xml";
3 xdoc.Load(xmlPath);
4
5 foreach (XmlNode node1 in xdoc.DocumentElement.SelectNodes("./Rent"))
6 {
7
8 foreach (XmlNode item in node1.SelectNodes("./Item"))
9 {
10 foreach (XmlAttribute xma in item.Attributes)
11 {
12
13 string strName = xma.Name;
14
15 string strValue = xma.Value;
16
17 }
18 }
19
20 }
21
22 foreach (XmlNode node2 in xdoc.DocumentElement.SelectNodes("./Sale"))
23 {
24 foreach (XmlNode item in node2.SelectNodes("./Item"))
25 {
26 foreach (XmlAttribute xma in item.Attributes)
27 {
28 string strName = xma.Name;
29 string strValue = xma.Value;
30 }
31 }
32 }
也许还有更好的办法,还没有想到。希望提供意见。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12639172/viewspace-462857/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/12639172/viewspace-462857/