2010-05-01 95 views
0

我总是很高兴能有机会使用linq到xml,然后我遇到了与命名空间相同的PITA问题。不知道我有什么问题,但我永远无法理解发生了什么。基本上,我只需要得到responseCode元素的值,到目前为止,我没有运气:(linq to xml and namespaces

<?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> 

回答

2

命名空间中的LINQ to XML是真正优雅的处理,IMO下面是一个例子:

XNamespace ns1 = "http://cbsv.ssa.gov/ws/datatype"; 
XDocument doc = XDocument.Load(...); 
string code = doc.Descendants(ns1 + "responseCode") 
       .Select(x => (string) x) 
       .First(); 

如果你想从上而下的工作,同时使用所涉及的命名空间,那也:

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"); 

只要是明确的,没有什么迫使您可以使用与XML中的命名空间前缀相同的变量名 - 我刚刚为了清晰起见而这样做了。

0

有了这样的XML:

<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> 

我用的是一样的查询:

tableInfo.TableName = (from element in xDoc.Descendants("Name") 
                select Convert.ToString(element.Value)).FirstOrDefault(); 

但是,如果你在代码中定义的命名空间,那么你可以得到更具体的,更快速:

XNamespace esri = "http://www.esri.com/schemas/ArcGIS/10.0"; 

tableInfo.TableName = xDoc.Element(esri + "DataElement").Element("Name").Value; 

你可以考虑在字符串中声明命名空间作为“esri:”的位置。 (在查询中无法使用冒号)。另外,在这样的文件中,我发现了多个标签,所以重要的是要获得正确的标签(或者至少只有一组标签)。在此之前,我结束了对于字段的冗余信息,这会搞乱创建SQL Server表。现在我可以定义我想要的与文档根目录相关的项目。