user2812233
user2812233

Reputation: 3

xpath can not get nodes with namespace

I have a huge xml document. When I test with xpath = //requestHeader returned result is below:

  <requestHeader> 
      <!--Optional:-->  
      <req:clientCode xmlns:req="http://www.ibb.com/ws/requestHeader">?</req:clientCode>  
      <!--Optional:-->  
      <req:clientUsername xmlns:req="http://www.ibb.com/ws/requestHeader">CC</req:clientUsername>  
      <!--Optional:-->  
      <req:channel xmlns:req="http://www.ibb.com/ws/requestHeader">?</req:channel>  
      <!--Optional:-->  
    </requestHeader>

And more, I need to get clientUsername value. Unfortunately //requestHeader//req:clientUsername returns empty string. what is wrong with it?

You can test with: http://www.xpathtester.com/test

Upvotes: 0

Views: 60

Answers (2)

DeadlyDan
DeadlyDan

Reputation: 699

put your namespace at the top the xml file like this:

<?xml version="1.0" encoding="UTF-8"?>
<requestHeader  xmlns:req="http://www.ibb.com/ws/requestHeader"> 
  <!--Optional:-->  
  <req:clientCode>?</req:clientCode>  
  <!--Optional:-->  
  <req:clientUsername>CC</req:clientUsername>  
  <!--Optional:-->  
  <req:channel>?</req:channel>  
  <!--Optional:-->  
</requestHeader>

now you can use xpath like so

 //requestHeader/req:clientUsername

Upvotes: 0

John B
John B

Reputation: 32949

Try specifying req in the namespaceContext:

XPath.setNamespaceContext

Upvotes: 1

Related Questions