LINQtoXML与XML处理全解析
立即解锁
发布时间: 2025-08-17 00:20:48 阅读量: 2 订阅数: 14 

### LINQ to XML 与 XML 处理全解析
#### 1. 创建 XML 文档
在实际开发中,我们常常需要创建 XML 数据并将其保存到文件中。下面为你详细介绍几种创建 XML 文档的方法。
##### 1.1 .NET 框架处理 XML 的方式
.NET 框架提供了多种处理 XML 文档的途径,具体使用哪种取决于你要完成的编程任务。.NET Framework 3.5 引入了一些类,用于操作和查询 XML 文件。其中,LINQ to XML 类极大地增强了对 W3C 文档对象模型(DOM)的支持。以下是一些常见的 LINQ to XML 类:
| 类名 | 描述 |
| ---- | ---- |
| XAttribute | 表示一个属性 |
| XDocument | 表示一个完整的 XML 树,继承自 XContainer,是所有可包含子元素的 XML 元素的基类 |
| XElement | 表示一个 XML 元素,是表示 XML 树的基本构造,也继承自 XContainer |
| XName | 表示属性和元素的名称 |
| XNode | 表示 XML 节点(如注释或元素)的基类 |
##### 1.2 传统创建 XML 树的方法
在早期的 .NET 版本中,创建 XML 树需要逐个元素地构建,代码如下:
```vb
Using fs As New FileStream("sample.xml", FileMode.Create)
Using w As XmlWriter = XmlWriter.Create(fs)
w.WriteStartDocument()
w.WriteStartElement("Products")
w.WriteStartElement("Product")
w.WriteAttributeString("id", "1001")
w.WriteElementString("ProductName", "Visual Basic 2008 Recipes")
w.WriteElementString("ProductPrice", "49.99")
w.WriteEndElement()
w.Flush()
End Using
End Using
```
这段代码会生成一个 `sample.xml` 文件,内容如下:
```xml
<?xml version="1.0" encoding="utf-8"?>
<Products>
<Product id="1001">
<ProductName>Visual Basic 2008 Recipes</ProductName>
<ProductPrice>49.99</ProductPrice>
</Product>
</Products>
```
##### 1.3 功能构造法创建 XML 树
.NET Framework 3.5 引入了 LINQ to XML 后,我们可以使用功能构造法更高效地创建 XML 树。示例代码如下:
```vb
Dim xmlTree As XElement = _
New XElement("Products", _
New XElement("Product", _
New XAttribute("id", "1001"), _
New XElement("ProductName", "Visual Basic 2008 Recipes"), _
New XElement("ProductPrice", "49.99")))
xmlTree.Save("products.xml")
```
这种方法只需在一条语句中嵌套创建 XElement 和 XAttribute 对象,就能构建整个 XML 树。
##### 1.4 使用 XML 文本和嵌入式表达式创建 XML 树
Visual Studio 2008 为 Visual Basic 开发者提供了更简便的方式,即使用 XML 文本和嵌入式表达式。示例代码如下:
```vb
Dim xmlTree = <Products>
<Product id="1001">
<ProductName>Visual Basic 2008 Recipes</ProductName>
<ProductPrice>49.99</ProductPrice>
</Product>
</Products>
```
当编译时,这段代码会先转换为功能构造法的代码。此外,我们还可以使用嵌入式表达式,例如:
```vb
Dim productID = 1001
Dim xmlTree = <Products>
<Product id=<%= productID %>>
<ProductName>Visual Basic 2008 Recipes</ProductName>
<ProductPrice>49.99</ProductPrice>
</Product>
</Products>
```
##### 1.5 完整代码示例
以下代码使用 XML 文本和嵌入式表达式创建一个 XML 树,并将其保存到文件中:
```vb
Imports System
Imports System.Xml.Linq
Namespace Apress.VisualBasicRecipes.Chapter07
Public Class Recipe07_01
Public Class Employee
Public EmployeeID As Integer
Public FirstName As String
Public LastName As String
Public Title As String
Public HireDate As DateTime
Public HourlyWage As Double
End Class
Public Shared Sub Main()
' Create a List to hold employees
Dim employeeList = New Employee() _
{New Employee With {.EmployeeID = 1, _
.FirstName = "Joed", _
.LastName = "McCormick", _
.Title = "Airline Pilot", _
.HireDate = DateTime.Now.AddDays(-25), _
.HourlyWage = 100.0}, _
New Employee With {.EmployeeID = 2, _
.FirstName = "Kia", _
.LastName = "Nakamura", _
.Title = "Super Genius", _
.HireDate = DateTime.Now.AddYears(-10), _
.HourlyWage = 999.99}, _
New Employee With {.EmployeeID = 3, _
.FirstName = "Romi", _
.LastName = "Brady", _
.Title = "Quantum Physicist", _
.HireDate = DateTime.Now.AddMonths(-15), _
.HourlyWage = 120.0}, _
New Employee With {.EmployeeID = 4, _
.FirstName = "Leah", _
.LastName = "Clooney", _
.Title = "Molecular Biologist", _
.HireDate = DateTime.Now.AddMonths(-10), _
.HourlyWage = 100.75}}
' Use XML literals to create the XML tree.
' Embedded expressions are used, with LINQ, to
' query the employeeList collection and build
' each employee node.
Dim employees = _
<Employees>
<%= From emp In employeeList _
Select _
<Employee id=<%= emp.EmployeeID %>>
<Name><%= emp.FirstName & " " & emp.LastName %></Name>
<Title><%= emp.Title %></Title>
<HireDate><%= emp.HireDate.ToString("MM/dd/yyyy") %></HireDate>
<HourlyRate><%= emp.HourlyWage %></HourlyRate>
</Employee> _
%>
</Employees>
' Save the XML tree to a file and then display it on
' the screen.
employees.Save("Employees.xml")
Console.WriteLine(employees.ToString())
' Wait to continue.
Console.WriteLine()
Console.WriteLine("Main method complete. Press Enter.")
Console.ReadLine()
End Sub
End Class
End Namespace
```
#### 2. 将 XML 文件加载到内存中
有时候,我们需要将 XML 文件的内容加载到内存中进行处理。可以使用 XElement 或 XDocument 类的 Load 方法来实现。
##### 2.1 XElement 和 XDocument 类的区别
XElement 类是处理 XML 树的主要类,但它不提供处理完整 XML 文档所有方面的属性和方法,如注释或处理指令。而 XDocument 类可以处理这些扩展信息。虽然 XElement 类可以包含任意数量的子元素,但 XDocument 类只能有一个子元素,通过 Root 属性访问。
##### 2.2 Parse 和 Load 方法
XElement 和 XDocument 类都包含 Parse 和 Load 方法。Parse 方法用于将字符串内容解析为 XElement 或 XDocument 对象,支持指定如何处理空白字符的重载。Load 方法用于将 XML 文件的完整内容加载到 XDocument 对象中,或将 XML 树加载到 XElement 对象中。该方法有多种重载,可以指定目标文件的路径、TextReader 实例或 XmlReader 实例。
##### 2.3 代码示例
以下代码将 `Employees.xml` 文件的内容加载到 XDocument 对象中,并显示文档声明和根元素的名称:
```vb
Imports System
Imports System.Xml.Linq
Namespace Apress.VisualBasicRecipes.Chapter07
Public Class Recipe07_02
Public Shared Sub Main()
' Load the Employees.xml and store the contents into an
' XDocument object.
Dim xmlDoc As XDocument = XDocument.Load("Employees.xml")
' Display the XML files declaration information.
Console.WriteLine("The document declaration is '{0}'", xmlDoc.Declaration.ToString)
' Display the name of the root element in the loaded
' XML tree. The Root property returns the top-level
' XElement, the Name property returns the XName class
' associated with Root and LocalName returns the name
' of the element as a string).
Console.WriteLine("The root element is '{0}'", xmlDoc.Root.Name.LocalName)
```
0
0
复制全文
相关推荐









