简体   繁体   中英

How to retrieve an element value from the xml using xpath?

How to retrieve the sitename element value from the below 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>

The below code I tried returned null:

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

Is the problem the Xml Namespace? Could I search regardless of the namespace values as sitename element has no namespace assigned to it?

I found the below code which works fine:

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

How to make it case-insensitive?

Try to look those links ;)

Case-insensitive XPath in .NET: http://blogs.msdn.com/shjin/archive/2005/07/22/442025.aspx

Use XPath to Perform a Case-Insensitive Search with MSXML: http://support.microsoft.com/kb/315719

For example :

XMLDoc.SelectNodes("Cars/car[contains(.,'Protan')]")

the result of above select should be equal with results of this select

XMLDoc.SelectNodes("Cars/car[contains(.,'protan')]")'

I had a similar problem. I was able to solve it by adding the namespace using a namespace manager.

Here's a similar Q/A: ( Using Xpath With Default Namespace in C# )

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM