c#linq to xml取一个元素

时间:2014-11-21 22:18:08

标签: c# xml linq linq-to-xml

我有这段代码

List<Customer> customersList =
                (
                    from e in XDocument.Load(file).Root.Elements("cust")
                    select new Customer
                    {
                        CustomerID = (int)e.Attribute("custid"),
                        FirstName = (string)e.Attribute("fname"),
                        LastName = (string)e.Attribute("lname"),
                        ShowsNumber = (int)e.Attribute("count_noshow"),
                        VisitNumber = (int)e.Attribute("count_resos"),
                        Cancellation = (int)e.Attribute("count_cancel"),

                    }).ToList();

如你所见,我正在提取属性,但我有三个(有时是四个)元素phone我想提取它们的第一个元素。

我试过了:

(string)e.Elements

但我不知道我现在应该做什么

你可以帮我吗?

XML

<cust memberid="12345678" lname="Smith" fname="Bill" email="bsmith@acme.com" emailoptin="0" mailoptin="0" cnotes="Likes the corner booth." birthday="2000-04-05" ><address memberid="12345678" address1="123 Main Street" address2=" " city="Carol Stream" state="IL" zip="60188-4746" country="United States" /> 
<phone countrycodeid="1" memberid="12345678" phonenumber="4156667777" phonetype="Home"/>
<phone countrycodeid="1" memberid="12345678" phonenumber="4157778888" phonetype="Mobile"/>
<phone countrycodeid="1" memberid="12345678" phonenumber="4158889999" phonetype="Work"/>
<custcode memberid="12345678" ccode="VIP"/> 

2 个答案:

答案 0 :(得分:1)

尝试:

XDocument doc = XDocument.Load(file);
XElement phoneElement = doc.Element("phone");

doc.Element(&#34; phone&#34;)将获取&#34; phone&#34;的第一个元素在xml文件中。

var phoneNumber = phoneElement.Attribute("phonenumber").Value.ToString();

使用Attribute方法获取属性的值。

答案 1 :(得分:0)

我认为应该这样做。

这假设始终至少有一个<phone>至少有一个<phonenumber>,我们只想要第一个:

List<Customer> customersList =
            (
                from e in XDocument.Load(file).Root.Elements("cust")
                select new Customer
                {
                    CustomerID = (int)e.Attribute("custid"),
                    FirstName = (string)e.Attribute("fname"),
                    LastName = (string)e.Attribute("lname"),
                    ShowsNumber = (int)e.Attribute("count_noshow"),
                    VisitNumber = (int)e.Attribute("count_resos"),
                    Cancellation = (int)e.Attribute("count_cancel"),

                    PhoneNumer = (string)e.Descendants("phone")
                                           .First()
                                           .Select(p=>p.Attributes("phonenumber").First().Value)

                }).ToList();