Get xsi: type with xpath value

I am trying to determine the correct XPath expression to return the value of the xsi:type attribute in the Body element. I tried what seems like no luck to everyone. Based on what I read, this seems close, but obviously this is not correct. Any quick guide so I can take a rest?

 //v20:Body/@xsi:type 

I want it to return v20:SmsMessageV1RequestBody

 <v20:MessageV1Request> <v20:Header> <v20:Source> <v20:Name>SOURCE_APP</v20:Name> <v20:ReferenceId>1326236916621</v20:ReferenceId> <v20:Principal>2001</v20:Principal> </v20:Source> </v20:Header> <v20:Body xsi:type="v20:SmsMessageV1RequestBody"> <v20:ToAddress>5555551212</v20:ToAddress> <v20:FromAddress>11111</v20:FromAddress> <v20:Message>TEST</v20:Message> </v20:Body> </v20:MessageV1Request> 
+6
source share
2 answers

As noted in the comments, you have two options:

  • Use local-name() to refer to target nodes ignoring namespaces
  • Register all namespaces correctly with the XPath engine

Here's how to do it in Java:

 XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContext ctx = new NamespaceContext() { public String getNamespaceURI(String prefix) { if ("v20".equals(prefix)) { return "testNS1"; } else if ("xsi".equals(prefix)) { return "http://www.w3.org/2001/XMLSchema-instance"; } return null; } public String getPrefix(String uri) { throw new UnsupportedOperationException(); } public Iterator getPrefixes(String uri) { throw new UnsupportedOperationException(); } }; xpath.setNamespaceContext(ctx); XPathExpression expr = xpath.compile("//v20:Body/@xsi:type"); System.out.println(expr.evaluate(doc, XPathConstants.STRING)); 

Please note that I accept the following namespace declarations:

 <v20:MessageV1Request xmlns:v20="testNS1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

You will need to update getNamespaceURI to use the actual values.

+2
source

All great answers / reviews. My actual problem seems to have resolved itself at night and with a fresh build in the morning. I will improve with feedback. Thanks to everyone.

0
source

Source: https://habr.com/ru/post/905669/


All Articles