使用XmlDocument.SelectNodes遍歷xml元素遇到的一個XPathException


使用XmlDocument類時候報錯:

未處理的XPathException:
需要命名空間管理器或 XsltContext。此查詢具有前綴、變量或用戶定義的函數。

需要使用XmlNamespaceManager類:Resolves, adds, and removes namespaces to a collection and provides scope management for these namespaces.

這是因為使用的soap文檔含有自己的命名空間。相同問題:http://bbs.csdn.net/topics/350101606

最終修改后的代碼:

 string soap = "";
                    soap += "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">";
                    soap += "<SOAP-ENV:Body>";
                    soap += "<AP-MSG:SubscriptionRequest xmlns:AP-MSG=\"http://www.vestas.dk/2001/04/ap\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\">";
                    soap += "<RequestBase ClientRequestHandle=\"41\" ReturnItemTime=\"false\" ReturnItemName=\"true\" CallbackURL=\"10.116.21.222:1055\" CallbackRate=\"PT10S\"/>";
                    soap += "<ItemRequestSpec MaxAge=\"PT0.1S\"/>";
                    soap += "<ItemList>";
                    foreach (IoTag tag in Tags)
                    {
                        soap += string.Format("<Item ItemName=\"{0}\"/>", tag.Name);
                    }
                    soap += "</ItemList>";
                    soap += "</AP-MSG:SubscriptionRequest>";
                    soap += "</SOAP-ENV:Body>";
                    soap += "</SOAP-ENV:Envelope>";
                    string subscriptionRequest = "";
                    subscriptionRequest += "POST * HTTP/1.1\r\n";
                    subscriptionRequest += "Content-Type:text/xml;charset=ISO-8859-1\r\n";
                    subscriptionRequest += "Connection:Keep-Alive\r\n";
                    subscriptionRequest += "SOAPAction:http://www.vestas.dk/2001/04/ap#SubscriptionRequest\r\n";
                    subscriptionRequest += string.Format("Content-Length:{0}\r\n", soap.Length);
                    subscriptionRequest += "\r\n";
                    subscriptionRequest += soap;

                    XmlDocument xDoc = new XmlDocument();
                    xDoc.LoadXml(soap);
                    XmlNamespaceManager nsMgr = new XmlNamespaceManager(xDoc.NameTable); nsMgr.AddNamespace("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/"); nsMgr.AddNamespace("AP-MSG", "http://www.vestas.dk/2001/04/ap"); nsMgr.AddNamespace("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
                    XmlElement xe = xDoc.DocumentElement;
                    XmlNodeList xnl = xDoc.SelectNodes("/SOAP-ENV:Envelope/SOAP-ENV:Body/AP-MSG:SubscriptionRequest/ItemList/Item", nsMgr);

            foreach (XmlNode item in xnl) { string s = item.Attributes["ItemName"].Value; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM