0%

C Sharp 补课笔记 -- LINQ to XML

LINQ to XML 是一种启用了 LINQ 的内存 XML 编程接口,支持在 .NET Framework 编程语言中处理 XML

简单示例

1
2
3
4
5
6
7
8
9
// Load the XML file from our project directory containing the purchase orders
var filename = "PurchaseOrder.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var purchaseOrderFilepath = Path.Combine(currentDirectory, filename);
XElement purchaseOrder = XElement.Load(purchaseOrderFilepath);
IEnumerable<string> partNos = from item in purchaseOrder.Descendants("Item")select (string) item.Attribute("PartNumber");

IEnumerable<string> partNos = purchaseOrder.Descendants("Item").Select(x => (string)
x.Attribute("PartNumber"));

创建XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
XElement contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144",
new XAttribute("Type", "Home")),
new XElement("phone", "425-555-0145",
new XAttribute("Type", "Work")),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);

LINQ to XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
XElement srcTree = new XElement("Root",
new XElement("Element", 1),
new XElement("Element", 2),
new XElement("Element", 3),
new XElement("Element", 4),
new XElement("Element", 5)
);
XElement xmlTree = new XElement("Root",
new XElement("Child", 1),
new XElement("Child", 2),
from el in srcTree.Elements()
where (int)el > 2
select el
);
Console.WriteLine(xmlTree);

XAttribute

创建包含属性的元素

1
2
3
4
5
XElement phone = new XElement("Phone",
new XAttribute("Type", "Home"),
"555-555-5555");
Console.WriteLine(phone);
//<Phone Type="Home">555-555-5555</Phone>

XML示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
XDocument d = new XDocument(
new XComment("This is a comment."),
new XProcessingInstruction("xml-stylesheet",
"href='mystyle.css' title='Compact' type='text/css'"),
new XElement("Pubs",
new XElement("Book",
new XElement("Title", "Artifacts of Roman Civilization"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implements"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("This is another comment.")
);
d.Declaration = new XDeclaration("1.0", "utf-8", "true");
Console.WriteLine(d);
d.Save("test.xml");
/*
<?xml version="1.0" encoding="utf-8"?>
<!--This is a comment.-->
<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>
<Pubs>
<Book>
<Title>Artifacts of Roman Civilization</Title>
<Author>Moreno, Jordao</Author>
</Book>
<Book>
<Title>Midieval Tools and Implements</Title>
<Author>Gazit, Inbar</Author>
</Book>
</Pubs>
<!--This is another comment.-->
*/