Linq to XML Parsing Help - getting elements?
Given the following:
- <ArrayOfWsParc开发者_如何学运维elDocIndexIAS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
- <wsParcelDocIndexIAS>
<locatorNum xmlns="http://xxx/webservices/wsDocumentIndex/">131312</locatorNum>
<docType xmlns="http://xxx/webservices/wsDocumentIndex/">KIOOLX_DOCINDEX</docType>
<docID xmlns="http://xxx/webservices/wsDocumentIndex/">234234</docID>
<docName xmlns="http://xxx/webservices/wsDocumentIndex/">Document - 7/1/2008</docName>
<fileExists xmlns="http://xxx/webservices/wsDocumentIndex/">true</fileExists>
<fileFormat xmlns="http://xxx/webservices/wsDocumentIndex/">PDF</fileFormat>
</wsParcelDocIndexIAS>
- <wsParcelDocIndexIAS>
<locatorNum xmlns="http://xxx/webservices/wsDocumentIndex/">131312</locatorNum>
I'm trying to retrieve each element with
var documentElements = from docels in root.Elements("wsParcelDocIndexIAS") select docels;
Then
foreach (XElement documentElement in documentElements)
{
XElement id = documentElement.Element("locatorNum");
XElement file_type = documentElement.Element("fileFormat");
Yet when id and file_type are null with the syntax I'm using to try to get their values.
What am I doing wrong here?
Thanks
You're not specifying the namespace. Try this:
XNamespace ns = "http://xxx/webservices/wsDocumentIndex/";
foreach (XElement documentElement in documentElements)
{
XElement id = documentElement.Element(ns + "locatorNum");
XElement file_type = documentElement.Element(ns + "fileFormat");
...
}
The elements in the XML are in the namespace "http://xxx/webservices/wsDocumentIndex/"
, but the names you give to the Element
method are not. You need to create an XName
with the namespace and the name (there's an overloaded +
operator for that):
XNamespace ns = "http://xxx/webservices/wsDocumentIndex/";
foreach (XElement documentElement in documentElements)
{
XElement id = documentElement.Element(ns + "locatorNum");
XElement file_type = documentElement.Element(ns + "fileFormat");
// ...
精彩评论