2014-02-21 187 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前缀。