2013-03-26 49 views
2

如何從下面的XML檢索sitename元素值?如何使用xpath從xml中檢索元素值?

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Header> 
    <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://localhost:63630/Service.svc</To> 
    <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IService/GetDemographic</Action> 
    </s:Header> 
    <s:Body> 
    <GetDemographic xmlns="http://tempuri.org/"> 
     <userIdentifier>first value</userIdentifier> 
     <sitename>second value</sitename> 
     <demographicName>third value</demographicName> 
    </GetDemographic> 
    </s:Body> 
</s:Envelope> 

下面的代碼我試圖返回null:

var xmlDocument = new XmlDocument(); 
xmlDocument.LoadXml(myXml); 
var result = xmlDocument.SelectNodes("//sitename"); 

是問題的XML命名空間?我可以搜索名稱空間值,因爲sitename元素沒有分配給它的名稱空間嗎?

我發現下面的代碼工作正常:

xmlDocument.SelectNodes("//*[local-name()='sitename']"); 

如何使它不區分大小寫?

+0

'「// s:Envelope/s:Body/GetDemographic/sitename」'?? – Nolonar 2013-03-26 14:30:57

+0

我希望它是通用的 – 2013-03-26 14:40:59

回答

0

我有類似的問題。我能夠通過使用名稱空間管理器添加名稱空間來解決此問題。

這裏有一個類似的Q/A:(Using Xpath With Default Namespace in C#

希望有所幫助。