C# 用Linq的方式實現對Xml檔案的基本操作(建立xml檔案、增刪改查xml檔案節點資訊)
阿新 • • 發佈:2018-12-10
1
private
static
void
GetXmlNodeInforOld(
string
xmlPath)
2
{
3
try
4
{
5
XDocument myXDoc
=
XDocument.Load(xmlPath);
6
XElement rootNode
=
myXDoc.Element(
"
Users
"
);
7
foreach
(XElement node
in
rootNode.Elements(
"
User
"
))
8
{
9
Console.WriteLine(
"
User ID = {0}
"
, node.Attribute(
"
ID
"
).Value);
10
11
string
name
=
node.Element(
"
name
"
).Value;
12
string
password
=
node.Element(
"
password
"
).Value;
13
string
description
=
node.Element(
"
description
"
).Value;
14
Console.WriteLine(
"
name = {0} \npassword = {1} \ndescription = {2}
"
, name, password, description);
15
}
16
}
17
catch
(Exception ex)
18
{
19
Console.WriteLine(ex.ToString());
20
}
21
}
22
23
private
static
void
GetXmlNodeInformation(
string
xmlPath)
24
{
25
try
26
{
27
//
定義並從xml檔案中載入節點(根節點)
28
XElement rootNode
=
XElement.Load(xmlPath);
29
//
查詢語句: 獲得根節點下name子節點(此時的子節點可以跨層次:孫節點、重孫節點......)
30
IEnumerable
<
XElement
>
targetNodes
=
from target
in
rootNode.Descendants(
"
name
"
)
31
select target;
32
foreach
(XElement node
in
targetNodes)
33
{
34
Console.WriteLine(
"
name = {0}
"
, node.Value);
35
}
36
37
//
查詢語句: 獲取ID屬性值等於"111111"並且函式子節點的所有User節點(並列條件用"&&"符號連線)
38
IEnumerable
<
XElement
>
myTargetNodes
=
from myTarget
in
rootNode.Descendants(
"
User
"
)
39
where
myTarget.Attribute(
"
ID
"
).Value.Equals(
"
111111
"
)
&&
myTarget.HasElements
40
select myTarget;
41
foreach
(XElement node
in
myTargetNodes)
42
{
43
Console.WriteLine(
"
name = {0}
"
, node.Element(
"
name
"
).Value);
44
Console.WriteLine(
"
password = {0}
"
, node.Element(
"
password
"
).Value);
45
Console.WriteLine(
"
description = {0}
"
, node.Element(
"
description
"
).Value);
46
}
47
}
48
catch
(Exception ex)
49
{
50
Console.WriteLine(ex.ToString());
51
}
52
}