Linq到XML导航问题

时间:2011-08-16 21:38:35

标签: xml linq

我知道这应该很简单,但我很难用LINQ to XML导航以下XML(我认为<soapenv:Body>搞砸了我)我此刻需要做的就是计算数字<addressData>元素。最后,我需要读取每个<addressData>元素中每个元素的值。

XML:

<soapenv:Body>
<getAddrResponse xmlns="http://urlhere.com/v1">
    <AddrResponse>
        <requestorId>123456</requestorId>
        <address>
            <addressCount>3</addressCount>
            <addressData>
                <addressLine1>123 MAIN ST</addressLine1>
                <cityName>HOLLYWOOD</cityName>
                <stateCode>CA</stateCode>
                <zipCode>90028</zipCode>
                <zipPlus4Code>1234</zipPlus4Code>
            </addressData>
            <addressData>
                <addressLine1>456 MAIN ST</addressLine1>
                <cityName>HOLLYWOOD</cityName>
                <stateCode>CA</stateCode>
                <zipCode>90028</zipCode>
                <zipPlus4Code>1234</zipPlus4Code>
            </addressData>
            <addressData>
                <addressLine1>789 MAIN ST</addressLine1>
                <cityName>HOLLYWOOD</cityName>
                <stateCode>CA</stateCode>
                <zipCode>90028</zipCode>
                <zipPlus4Code>1234</zipPlus4Code>
            </addressData>
        </address>
    </AddrResponse>
</getAddrResponse>
</soapenv:Body>

2 个答案:

答案 0 :(得分:1)

您需要考虑名称空间和名称空间前缀,包括声明soapenv

var xml =  "<soapenv:Body xmlns:soapenv=\""
          +"http://www.w3.org/2001/12/soap-envelope\">...</soapenv:Body>";
var doc = XDocument.Parse(xml);
XNamespace ns = "http://urlhere.com/v1";

var addressDatas = doc.Root.Descendants(ns+"addressData");

var count = addressDatas.Count();

var firstAddressLine = addressDatas.First().Element(ns+"addressLine1").Value;

答案 1 :(得分:0)

您的XML目前是非法的:您的外部命名空间未定义。所以假设您的XML非常像

<soapenv:Body xmlns:soapenv="foo.com">
 ...

您可以获得addressData这样的计数:

XDocument doc = XDocument.Load("test.xml");
XNamespace someNamespace = "http://urlhere.com/v1";
int addressCount = doc.Descendants(someNamespace + "addressData").Count();