2010-05-01 87 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表。現在我可以定義我想要的與文檔根目錄相關的項目。