linq to xml and namespaces
I'm always so excited to get a cha开发者_如何学JAVAnce to use linq to xml and then I run into the same PITA issue with namespaces. Not sure what is wrong with me but I can never quite grok what is going on. Basically I just need to get the value of the responseCode element and so far I have had no luck :(
<?xml version="1.0" encoding="IBM437"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns1:ActionResponse xmlns:ns1="http://cbsv.ssa.gov/ws/datatype">
<ns1:responseCode>0000</ns1:responseCode>
<ns1:responseDescription>Successful</ns1:responseDescription>
</ns1:ActionResponse>
</soapenv:Body>
</soapenv:Envelope>
Namespaces in LINQ to XML are really elegantly handled, IMO. Here's an example:
XNamespace ns1 = "http://cbsv.ssa.gov/ws/datatype";
XDocument doc = XDocument.Load(...);
string code = doc.Descendants(ns1 + "responseCode")
.Select(x => (string) x)
.First();
If you want to work down from the top, using both of the namespaces involved, that's okay too:
XNamespace ns1 = "http://cbsv.ssa.gov/ws/datatype";
XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
XDocument doc = XDocument.Load(...);
string code = (string) doc.RootElement
.Element(soapenv + "Body")
.Element(ns1 + "ActionResponse")
.Element(ns1 + "responseCode");
Just to be clear, there's nothing forcing you to use the same variable name as the namespace prefix in the XML - I've just done so for clarity.
With XML like this:
<esri:DataElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:esri="http://www.esri.com/schemas/ArcGIS/10.0" xsi:type="esri:DEFeatureClass">
<CatalogPath>\counties</CatalogPath>
<Name>counties</Name>
…
</esri:DataElement>
I was using queries like:
tableInfo.TableName = (from element in xDoc.Descendants("Name")
select Convert.ToString(element.Value)).FirstOrDefault();
But if you define the namespace in your code, then you can get more specific, faster:
XNamespace esri = "http://www.esri.com/schemas/ArcGIS/10.0";
tableInfo.TableName = xDoc.Element(esri + "DataElement").Element("Name").Value;
You can think of declaring the namespace as taking the place of “esri:” in strings. (There’s no way to use a colon in a query either). Also, in a file like this, I was finding multiple occurrences of tags so it’s important to get the right ones (or at least just one set). Before, I was ending up with redundant info for fields, which would mess up creating a SQL Server table. Now I can define which item I want related to the document root.
精彩评论