LINQ 项目-XML 集成
【IT168技术文档】
用于 XML 的 .NET 语言集成查询 (XLinq) 允许使用标准查询操作符以及特定于树的操作符(提供类似于 XPath 的子代、父代和同辈导航)来查询 XML 数据。它提供了有效的 XML 内存中表示形式,该表示形式与现有的 System.Xml 读取器/写入器基础结构集成在一起,比 W3C 文档更易于使用。将 XML 与查询相集成的大部分工作由以下三个类型执行:XName、XElement 和 XAttribute。
XName 提供一种易于使用的方法来处理命名空间限定的标识符 (QName)(既用作元素又用作属性名)。XName 可以透明地处理高效的标识符原子化,并在需要 QName 时允许使用符号或纯字符串。
XML 元素和属性分别通过 XElement 和 XAttribute 表示。XElement 和 XAttribute 支持普通的结构语法,以允许开发人员使用自然语法编写 XML 表达式:
这对应于以下 XML:var e = new XElement("Person", new XAttribute("CanCode", true), new XElement("Name", "Loren David"), new XElement("Age", 31)); var s = e.ToString();
请注意,创建 XML 表达式不需要基于 DOM 的工厂模式,并且 ToString 实现会生成 XML 文本。XML 元素还可以从现有的 XmlReader 或字符串文字生成:<Person CanCode="true"> ? <Name>Loren David</Name> ? <Age>31</Age> </Person>
XElement 还支持使用现有的 XmlWriter 类型发出 XML。var e2 = XElement.Load(xmlReader); var e1 = XElement.Parse( @"<Person CanCode='true'> <Name>Loren David</Name> <Age>31</Age> </Person>");
XElement 与查询操作符吻合,从而允许开发人员针对非 XML 信息编写查询,以及通过将 XElements 构建到 select 子句的正文中来生成 XML 结果:
该查询将返回一个 XElement 序列。要允许 XElement 的生成超出这种类型的查询结果,XElement 构造函数应允许将元素序列直接作为参数进行传递:var query = from p in people where p.CanCode select new XElement("Person", new XAttribute("Age", p.Age), p.Name);
该 XML 表达式将生成以下 XML:var x = new XElement("People", from p in people where p.CanCode select new XElement("Person", new XAttribute("Age", p.Age), p.Name));
上述语句可以直接转换为 Visual Basic。但是,Visual Basic 9.0 还支持使用 XML 文字,这允许直接从 Visual Basic 使用声明性 XML 语法来表达查询表达式。上面的示例可以通过以下 Visual Basic 语句生成:<People> <Person Age="11">Allen Frances</Person> <Person Age="59">Connor Morgan</Person> </People>
Dim x = _ <People> Select <Person Age=(p.Age) >p.Name</Person> _ From p In people _ Where p.CanCode </People>
到目前为止,这些示例已经展示了如何使用语言集成的查询生成 新的 XML 值。XElement 和 XAttribute 类型还简化了从 XML 结构提取 信息的过程。XElement 还提供了访问器方法,以便允许将查询表达式应用于传统的 XPath 轴。例如,以下查询仅从上述 XElement 中提取名称:
要从 XML 中提取结构化值,我们只需在 select 子句中使用对象初始值设定项表达式:IEnumerable justNames = from e in x.Descendants("Person") select e.Value; //justNames = ["Allen Frances", "Connor Morgan"]
请注意,XAttribute 和 XElement 都支持显式转换操作符将文本值作为基元类型来提取。要处理缺失数据,我们只需强制转换为可以为空的类型:IEnumerable persons = from e in x.Descendants("Person") select new Person { Name = e.Value, Age = (int)e.Attribute("Age") };
IEnumerable persons = from e in x.Descendants("Person") select new Person { Name = e.Value, Age = (int?)e.Attribute("Age") ?? 21 };
在本例中,当 Age 属性缺失时,我们使用默认值 21。
Visual Basic 9.0 为 XElement 的 Elements、Attribute 和 Descendants 等访问器方法提供了直接的语言支持,以允许使用更为简洁、直接的语法来访问基于 XML 的数据。我们可以使用此功能来编写前面的 C# 语句,如下所示:
在 Visual Basic 中,表达式 e.Name 通过名称 Name 查找所有的 XElement,表达式 e.@Age 通过名称 Age 查找 XAttribute,而表达式 x...Person 则通过名称 Person 获得 x 的 Descendants 集合中的所有项。Dim persons = _ Select new Person { .Name = e.Name .Age = e.@Age ?? 21 } From e In x...Person
0
相关文章