【问题标题】:How to parse xml data with dynamic linq如何使用动态 linq 解析 xml 数据
【发布时间】:2015-07-22 18:25:12
【问题描述】:

我正在读取一个 xml 文件并通过以下方式通过 LINQ 查询

XDocument document = XDocument.Load(xmlFilePath);
var query = document.Descendants("orders").Select(c => c);
query = query.OrderBy(sortColumn + " " + OrderDirection);

query = query.Skip(lowerPageBoundary - 1 * rowsPerPage).Take(rowsPerPage);

DataTable table = query.ToList().ConvertToDataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
//adapter.Fill(table);
return table;

但出现错误“XElement”类型中不存在任何属性或字段“OrderID”(在索引 0 处)

这是我通过 LINQ 查询的示例 xml

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Orders>
    <OrderID>10248</OrderID>
    <CustomerID>VINET</CustomerID>
    <EmployeeID>5</EmployeeID>
    <OrderDate>1996-07-04T00:00:00</OrderDate>
    <RequiredDate>1996-08-01T00:00:00</RequiredDate>
    <ShippedDate>1996-07-16T00:00:00</ShippedDate>
    <ShipVia>3</ShipVia>
    <Freight>32.3800</Freight>
    <ShipName>Vins et alcools Chevalier</ShipName>
    <ShipAddress>59 rue de l'Abbaye</ShipAddress>
    <ShipCity>Reims</ShipCity>
    <ShipPostalCode>51100</ShipPostalCode>
    <ShipCountry>France</ShipCountry>
  </Orders>
</Root>

我在下面的查询中使用了这个,但仍然没有运气

var query = document.Descendants("orders")
                    .OrderBy(String.Format("Element(\"{0}\").Value {1}", sortColumn, OrderDirection))
                    .Skip(lowerPageBoundary - 1 * rowsPerPage)
                    .Take(rowsPerPage);

【问题讨论】:

  • 你试过 document.root.Descendants("Orders")
  • @w.b 我使用了动态链接,这种 order by 子句是有效的。

标签: c# xml linq dynamic-linq


【解决方案1】:

您收到错误的原因是因为XML tags are case sensitive。

链接摘录(已修改以匹配您问题中的示例):

XML 标签区分大小写。标签 与标签 不同。

您的查询正在搜索不存在的元素“订单”。更新您的查询:

XDocument document = XDocument.Load(xmlFilePath);
var query = document.Descendants("Orders").Select(c => c);

更新:

根据您的 cmets,错误实际上源于尝试通过 IEnumerabe&lt;XElement&gt; 中的“OrderID”进行排序。 “OrderID”实际上是每个XElement 的子元素。

对此进行更多研究可能会有所帮助。在谷歌搜索的帮助下,我的结果表明 System.Linq.Dynamic 库不是为与 XML 一起使用而设计的。

看到这个SO Question OP 结束的地方:

我终于让它工作了。我放弃了我原来的方法,因为到目前为止我不相信它甚至打算与 Xml 一起使用。我在任何地方都很少看到反对该声明的帖子。

将 XML 读入 DataSet 怎么样?

DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFilePath);

string sort = sortColumn + " " + OrderDirection;

DataTable table = dataSet.Tables["Orders"].Select("", sort)
                                          .Skip(lowerPageBoundary - 1 * rowsPerPage)
                                          .Take(rowsPerPage)
                                          .CopyToDataTable();

table.Locale = System.Globalization.CultureInfo.InvariantCulture;

【讨论】:

  • 对不起,我使用的类型是订单而不是订单,但仍然出现错误
  • 查看按子句顺序使用 string.format 的最后一个代码
  • 如果您更新您的问题以在此处反映您的 cmets,这将对所有人都有帮助。
猜你喜欢
  • 2010-11-25
  • 1970-01-01
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多