2014-02-21 185 views
1

我一直在試圖解析一些信息,並遵循從http://lakenine.com/reading-xml-with-namespaces-using-linq/精彩勸我敢肯定,這是接近的,但我沒有得到任何結果顯示。沒有錯誤,只是沒有結果。斷點和檢查變量顯示docx具有適當的信息,但我的for循環會被忽略。我玩過多種變體,只會造成代碼崩潰。我相信問題出現在XPathSelectElements參數中,但不知道還有什麼可以嘗試的。 在這個階段,所有我需要的是道理,但我以後需要重用的代碼,可能有多個結果返回。請指教,謝謝您提前:解析SOAP XML名稱空間

 string sampleXML = String.Concat(
       "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", 
       " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", 
       " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">", 
       " <soap12:Body>", 
       " <BeginSessionV2Response xmlns=\"http://ws.jobboard.com/jobs/\">", 
       " <BeginSessionV2Result>ca5522fb93ef499f8ed010a5f4153af7-446298346-SB-4</BeginSessionV2Result>", 
       " </BeginSessionV2Response>", 
       " </soap12:Body>", 
       " </soap12:Envelope>" 
       ); 

       XmlReader reader = XmlReader.Create(new StringReader(sampleXML)); 
       System.Xml.XmlNameTable nameTable = reader.NameTable; 
       System.Xml.XmlNamespaceManager namespaceManager = new System.Xml.XmlNamespaceManager(nameTable); 

       namespaceManager.AddNamespace("soap12", "http://www.w3.org/2001/XMLSchema-instance/"); 
       XElement docx = XElement.Load(reader); 

       string vbResultz = "start: "; 
       var sessionKey = from pn 
       in docx.XPathSelectElements("soap12:Body/BeginSessionV2Response/BeginSessionV2Result", namespaceManager) 
        select (string)pn; 
         foreach (string pn in sessionKey) 
         { 
          vbResultz += pn; 
         } 

         ViewBag.REsultz = vbResultz;   


     return View(); 
    } 

回答

0

首先,你加入soap12前綴有錯誤的URI。添加命名空間namespaceManager這樣:

namespaceManager.AddNamespace("soap12", "http://www.w3.org/2003/05/soap-envelope"); 
namespaceManager.AddNamespace("ns", "http://ws.jobboard.com/jobs/"); 

然後你可以用它們在XPath表達式是這樣的:

...... 
docx.XPathSelectElements("soap12:Body/ns:BeginSessionV2Response/ns:BeginSessionV2Result", namespaceManager) 
...... 

注意<BeginSessionV2Response>具有默認命名空間(xmlns屬性沒有前綴),因此該元素和它的在默認名稱空間內沒有考慮前綴的後代。因此,我們需要在上面的XPath查詢表達式中添加ns前綴。