I know this should be simple but I am having a difficult time navigating the following XML with LINQ to XML (I think the <soapenv:Body>
is messing me up) All I need to do at this point is count the number of <addressData>
elements. Eventually I will need to read the values of each element within each <addressData>
element.
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>900开发者_StackOverflow28</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>
You need to take namespaces and namespace prefixes into account, including declaring 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;
Your XML is currently illegal: your outer namespace is not defined. So assuming your XML is really like
<soapenv:Body xmlns:soapenv="foo.com">
...
You can get the addressData
count like this:
XDocument doc = XDocument.Load("test.xml");
XNamespace someNamespace = "http://urlhere.com/v1";
int addressCount = doc.Descendants(someNamespace + "addressData").Count();
精彩评论