技术开发 频道

LINQ 项目-XML 集成


  到目前为止,这些示例已经展示了如何使用语言集成的查询生成 新的 XML 值。XElement 和 XAttribute 类型还简化了从 XML 结构提取 信息的过程。XElement 还提供了访问器方法,以便允许将查询表达式应用于传统的 XPath 轴。例如,以下查询仅从上述 XElement 中提取名称:
IEnumerable justNames = from e in x.Descendants("Person") select e.Value; //justNames = ["Allen Frances", "Connor Morgan"]
  要从 XML 中提取结构化值,我们只需在 select 子句中使用对象初始值设定项表达式:
IEnumerable persons = from e in x.Descendants("Person") select new Person { Name = e.Value, Age = (int)e.Attribute("Age") };
  请注意,XAttribute 和 XElement 都支持显式转换操作符将文本值作为基元类型来提取。要处理缺失数据,我们只需强制转换为可以为空的类型:

  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# 语句,如下所示:
Dim persons = _ Select new Person { .Name = e.Name .Age = e.@Age ?? 21 } From e In x...Person
  在 Visual Basic 中,表达式 e.Name 通过名称 Name 查找所有的 XElement,表达式 e.@Age 通过名称 Age 查找 XAttribute,而表达式 x...Person 则通过名称 Person 获得 x 的 Descendants 集合中的所有项。
0
相关文章