如何使用linq获取根节点属性值
我有以下 XML。如何使用 LINQ 读取根节点属性值及其后代?我正在尝试从根节点读取“dId”和“dTime”,从客户元素和订单号读取“id”。
<?xml version="1.0" encoding="utf-8" ?>
<Customers dId="wqwx" dTime="10-9-09 11:23">
<Customer id="1">
<Orders>
<Order number="22" status="ok">
</Orders>
</Customer>
</Customers>
我尝试了以下代码,但它不起作用。
XDocument doc= XDocument.Load(@"C:\Customers.xml");
var q = from c in doc.Descendants("Customers")
select new
{
dID = c.Attribute("dId"),
dTime = c.Attribute("dTime");
}
I have the following XML. How to read the root node attribite value and it's decendents using LINQ? I am trying to read "dId" and "dTime" from root node, "id" from Customer element and Order number.
<?xml version="1.0" encoding="utf-8" ?>
<Customers dId="wqwx" dTime="10-9-09 11:23">
<Customer id="1">
<Orders>
<Order number="22" status="ok">
</Orders>
</Customer>
</Customers>
I tried the following code but it doesn't work.
XDocument doc= XDocument.Load(@"C:\Customers.xml");
var q = from c in doc.Descendants("Customers")
select new
{
dID = c.Attribute("dId"),
dTime = c.Attribute("dTime");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先,修复您的 xml (
)那么,你的 linq 应该看起来像这样......
你应该 dl LinqPad ...它可以让你做Linq 即时查询,甚至针对 SQL 数据库。然后,一旦获得所需的结果,请将 linq 复制并粘贴到源代码中。
first, fix your xml (
<Order .... />
)then, your linq should look like this....
you should dl LinqPad... it lets you do Linq queries on the fly, even agains SQL databases. Then, once you get the results you want, copy and past your linq into your source code.
您必须以以下方式结束订单标记:
/>
xDoc.Descendants("Customers")
应该与xDoc.Elements("Customers") 一样有效
。Chris,使用
.Elements
有什么具体优势吗?You have to end the order tag with:
/>
xDoc.Descendants("Customers")
should work as well asxDoc.Elements("Customers")
.Chris, is there a specific advantage to using
.Elements
?您无法使用 LINQ 访问根标记。
下面的代码可以满足您的需求(我还包含了一个格式良好的 xml 文件):
以及 xml 文件:
You can't use LINQ to access the root tag.
The code below does what you want (I included a well formed xml file as well):
and the xml file:
控制台输出:
==================================
dId = wqwx
时间 = 10-9-09 11:23
客户 ID = 1
订单数 = 22
请按任意键继续。 。 .
Console Output:
================================
dId = wqwx
dTime = 10-9-09 11:23
CustomerID = 1
OrderCount = 22
请按任意键继续. . .
它不能按照您编写的方式工作:在打印上面的代码时会抱怨匿名类型。
但是,通过这个简单的修改版本
d.Document.Root.Attribute("dId").Value;
,您可以将其分配给一个字符串。It does not work the way you wrote it: while printing the above code would complain about anonymous type.
However, with this simple modified version
d.Document.Root.Attribute("dId").Value;
you can assign it to a string.