如何从嵌套节点中检索xml数据

时间:2017-03-10 07:17:36

标签: c# asp.net xml

var fb = 'https://www.facebook.com/XYZ'

console.log(
  fb.replace(/^https?:\/\/(?:www.)?facebook.com(?=\/)/, '') //=> '/XYZ'
)

如何检索OrderID,CustomerID和OrderDate?我已经尝试了几个小时了。有人能帮我吗?谢谢!

<CustomerOrders>
  <Customers>
    <CustomerID>ALFKI</CustomerID>
    <Orders>
      <OrderID>10643</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-08-25</OrderDate>
    </Orders>
    <Orders>
      <OrderID>10692</OrderID>
      <CustomerID>ALFKI</CustomerID>
      <OrderDate>1997-10-03</OrderDate>
    </Orders>
    <CompanyName>Alfreds Futterkiste</CompanyName>
  </Customers>
  <Customers>
    <CustomerID>ANATR</CustomerID>
    <Orders>
      <OrderID>10308</OrderID>
      <CustomerID>ANATR</CustomerID>
      <OrderDate>1996-09-18</OrderDate>
    </Orders>
    <CompanyName>Ana Trujillo Emparedados y helados</CompanyName>
  </Customers>
</CustomerOrders>

3 个答案:

答案 0 :(得分:1)

您可以使用XDocument类及其后代。您可以使用XPath表达式深入研究代码:

e.g。

using System.Xml.Linq
using System.Xml.XPath

.... 
XDocument doc= XDocument.Load("sample.xml");
XElement root= doc.Element("CustomerOrders");
var result= root.XPathSelectElements("Customers/CustomerId");
foreach(var customerid in result)
    {
    .....
    }

根据您想要达到的目标,这应该让您走在正确的轨道上。当我输入答案时,另一个答案建议使用XmlDocument类。这应该也可以,但是当使用XDocument时,您可以使用Linq,这会增加很多灵活性。

答案 1 :(得分:0)

onCreate()

答案 2 :(得分:0)

以下是使用Xml Linq的所有内容

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication47
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("Customers").Select(x => new
            {
                customerID = (string)x.Element("CustomerID"),
                companyName = (string)x.Element("CompanyName"),
                orders = x.Elements("Orders").Select(y => new {      
                   orderID = (int)y.Element("OrderID"),
                   customerID = (string)y.Element("CustomerID"),
                   date =  (DateTime)y.Element("OrderDate")
                }).ToList()
            }).ToList();
        }
    }
}