2013-01-23 29 views
1

改變選擇XML節點我不得不從WCF請求OperationContext.Current.RequestContext.RequestMessage.ToString()其中的名稱空間是請求之間在WCF

的問題是,命名空間是量變到質變的請求之間的前綴選擇特定的節點:

因此,一旦它是:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> 
    <s:Body> 
    </s:Body> 
</s:Envelope> 

和其他時間,它是:

<soapenv:Envelope xmlns:mes="MessageContracts" xmlns:req="RequestMessages" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soapenv:Body> 
    </soapenv:Body> 
</soapenv:Envelope> 

我怎樣才能保證我總是能正確地獲得Body節點?

+0

它不是正在改變的命名空間('http:// schemas.xmlsoap.org/soap/envelope /'),而是命名空間前綴(從's'到'soapenv')。 – flup

回答

0

只要節點始終如一地使用相同的名稱空間(它們在您的示例中),哪些前綴是無關緊要的。你只需要確保你正確地創建了命名空間的prefix->命名空間映射,當你做你的選擇:

下面的代碼將正常運行,是爲您的例子個XML的:

// assuming XmlDocument doc has already been loaded with the XML response 
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable); 
nsm.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); 
XmlNode body = doc.SelectSingleNode("/soap:Envelope/soap:Body", nsm); 

Working ideone example

+0

嗨。謝謝,我的想法完全一樣,而且我在開始時確實如此 - 但它不起作用,這就是我發佈的目的。讓我再檢查一下,如果我沒有犯一些簡單的錯誤 – Johnny

+0

呵呵。這個問題真的出現在我的Xpath語句中。我正在選擇xmlReq.SelectSingleNode(「bd:Body」,ns) - 它給出了空結果! 但是不應該選擇文檔中的所有Body節點? – Johnny

+0

不,「bd:Body」只會選擇位於上下文節點正下方的Body節點。 '// bd:Body'會選擇文檔中的所有Body節點。 – JLRishe

0

如果使用XPATH選擇節點,則可以通過在local-name()的基礎上進行選擇來選擇節點時忽略名稱空間(及其縮寫前綴)。還有就是這個在下面的文章SO一個例子: -

對於上述XML文檔,下面的XPath查詢將返回計數1兩個文件。

count(/*[local-name() = 'Envelope']/*[local-name() = 'Body']) 
+0

尚未檢查該解決方案,但很有趣。我會看看。 感謝您的回答 – Johnny

+0

沒有問題。如果它有用,+1會很棒:)我正在努力製作2k。 –

相關問題