如何使用linq获取根节点属性值

发布于 2024-08-07 18:39:04 字数 643 浏览 5 评论 0原文

我有以下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

似狗非友 2024-08-14 18:39:04

首先,修复您的 xml ()
那么,你的 linq 应该看起来像这样......

// .Elements(...) selects all elements of type "Customer"
    var q = from c in xDoc.Elements("Customers") 
    select new
    {
        dID = c.Attribute("dId"), 
        dTime = c.Attribute("dTime")
    }; 

你应该 dl LinqPad ...它可以让你做Linq 即时查询,甚至针对 SQL 数据库。然后,一旦获得所需的结果,请将 linq 复制并粘贴到源代码中。

first, fix your xml (<Order .... />)
then, your linq should look like this....

// .Elements(...) selects all elements of type "Customer"
    var q = from c in xDoc.Elements("Customers") 
    select new
    {
        dID = c.Attribute("dId"), 
        dTime = c.Attribute("dTime")
    }; 

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.

赢得她心 2024-08-14 18:39:04

您必须以以下方式结束订单标记:/>

xDoc.Descendants("Customers") 应该与 xDoc.Elements("Customers") 一样有效

Chris,使用 .Elements 有什么具体优势吗?

You have to end the order tag with: />

xDoc.Descendants("Customers") should work as well as xDoc.Elements("Customers").

Chris, is there a specific advantage to using .Elements?

三五鸿雁 2024-08-14 18:39:04

您无法使用 LINQ 访问根标记。
下面的代码可以满足您的需求(我还包含了一个格式良好的 xml 文件):

using System;
using System.Linq;
using System.Xml.Linq;

namespace ReadXmlSpike
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reading file...");
            XDocument doc = XDocument.Load("Customers.xml");
            var customers =
                new
                    {
                        DID = (string) doc.Element("Customers").Attribute("did"),
                        DTime = (DateTime) doc.Element("Customers").Attribute("dTime"),
                        Customers = from customerxml in doc.Descendants("Customer")
                                    select
                                        new
                                            {
                                                ID = (string)customerxml.Attribute("id"),
                                                Orders = from orderxml in customerxml.Descendants("Order")
                                                         select
                                                             new
                                                                 {
                                                                     Number =(string) orderxml.Attribute("number")
                                                                 }
                                            }
                    };
            Console.WriteLine("Customersfile with id: {0} and time {1}",customers.DID,customers.DTime);
            foreach (var customer in customers.Customers)
            {
                Console.WriteLine("Customer with id {0} has the following orders:",customer.ID);
                foreach (var order in customer.Orders)
                {
                    Console.WriteLine("Order with number {0}",order.Number);
                }
            }
            Console.ReadLine();
        }
    }
}

以及 xml 文件:

<?xml version="1.0" encoding="utf-8" ?>
<Customers did="www" dTime="10-09-09 11:23">
  <Customer id="1">
    <Orders>
      <Order number="22" status="ok"/>
      <Order number="23" status="bad"/>
    </Orders>
  </Customer>
  <Customer id="2">
    <Orders>
      <Order number="24" status="ok"/>
      <Order number="25" status="bad"/>
    </Orders>
  </Customer>
</Customers>

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):

using System;
using System.Linq;
using System.Xml.Linq;

namespace ReadXmlSpike
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reading file...");
            XDocument doc = XDocument.Load("Customers.xml");
            var customers =
                new
                    {
                        DID = (string) doc.Element("Customers").Attribute("did"),
                        DTime = (DateTime) doc.Element("Customers").Attribute("dTime"),
                        Customers = from customerxml in doc.Descendants("Customer")
                                    select
                                        new
                                            {
                                                ID = (string)customerxml.Attribute("id"),
                                                Orders = from orderxml in customerxml.Descendants("Order")
                                                         select
                                                             new
                                                                 {
                                                                     Number =(string) orderxml.Attribute("number")
                                                                 }
                                            }
                    };
            Console.WriteLine("Customersfile with id: {0} and time {1}",customers.DID,customers.DTime);
            foreach (var customer in customers.Customers)
            {
                Console.WriteLine("Customer with id {0} has the following orders:",customer.ID);
                foreach (var order in customer.Orders)
                {
                    Console.WriteLine("Order with number {0}",order.Number);
                }
            }
            Console.ReadLine();
        }
    }
}

and the xml file:

<?xml version="1.0" encoding="utf-8" ?>
<Customers did="www" dTime="10-09-09 11:23">
  <Customer id="1">
    <Orders>
      <Order number="22" status="ok"/>
      <Order number="23" status="bad"/>
    </Orders>
  </Customer>
  <Customer id="2">
    <Orders>
      <Order number="24" status="ok"/>
      <Order number="25" status="bad"/>
    </Orders>
  </Customer>
</Customers>
柠檬心 2024-08-14 18:39:04
    XDocument d = XDocument.Parse(@"<?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>");
    var cu = d.Root.Elements().Where(n => n.Name == "Customer");


    var c = from cc in cu
            select new
            {
                dId = cc.Document.Root.Attribute("dId").Value,
                dTime = cc.Document.Root.Attribute("dTime").Value,
                ID = cc.Attribute("id").Value,
                number = cc.Element("Orders").Element("Order").Attribute("number").Value
            };

    foreach (var v in c)
    {
        Console.WriteLine("dId \t\t= {0}", v.dId);
        Console.WriteLine("dTime \t\t= {0}", v.dTime);
        Console.WriteLine("CustomerID \t= {0}", v.ID);
        Console.WriteLine("OrderCount \t= {0}", v.number);
    }

控制台输出:
==================================
dId = wqwx
时间 = 10-9-09 11:23
客户 ID = 1
订单数 = 22
请按任意键继续。 。 .

    XDocument d = XDocument.Parse(@"<?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>");
    var cu = d.Root.Elements().Where(n => n.Name == "Customer");


    var c = from cc in cu
            select new
            {
                dId = cc.Document.Root.Attribute("dId").Value,
                dTime = cc.Document.Root.Attribute("dTime").Value,
                ID = cc.Attribute("id").Value,
                number = cc.Element("Orders").Element("Order").Attribute("number").Value
            };

    foreach (var v in c)
    {
        Console.WriteLine("dId \t\t= {0}", v.dId);
        Console.WriteLine("dTime \t\t= {0}", v.dTime);
        Console.WriteLine("CustomerID \t= {0}", v.ID);
        Console.WriteLine("OrderCount \t= {0}", v.number);
    }

Console Output:
================================
dId = wqwx
dTime = 10-9-09 11:23
CustomerID = 1
OrderCount = 22
请按任意键继续. . .

独行侠 2024-08-14 18:39:04

它不能按照您编写的方式工作:在打印上面的代码时会抱怨匿名类型。

但是,通过这个简单的修改版本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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文