Skip to content

Instantly share code, notes, and snippets.

@KomanRudden
Last active May 18, 2016 08:49
Show Gist options
  • Save KomanRudden/420e2b48b4a07db1357936fb4953bbfb to your computer and use it in GitHub Desktop.
Save KomanRudden/420e2b48b4a07db1357936fb4953bbfb to your computer and use it in GitHub Desktop.
XPath with namespace
<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ods.co.za" xsi:schemaLocation="http://www.ods.ca.za PersonService.xsd">
<person isn="3101111" userID="SOFXX" timestamp="2010-02-27T07:36:48+02:00" millis="200">
<partyID> 2831762 </partyID>
<idNumber type="ID_NUMBER">
<number> 7777777777777 </number>
</idNumber>
<incomeTaxNumber> 1091919191 </incomeTaxNumber>
<title> Ms </title>
<surname> FIRST </surname>
<initials> AT </initials>
<firstName> ASSISTANCE </firstName>
<middleNames> MIDDLE </middleNames>
<gender> FEMALE </gender>
<dateOfBirth> 1970-06-05 </dateOfBirth>
<language> ENGLISH </language>
<maritalStatus> MARRIED </maritalStatus>
<contactDetails preferredContact="POST">
<addresses correspondanceAddress="POSTAL">
<address type="POSTAL" timestamp="2010-02-27T07:36:48+02:00" millis="200">
<line1> PO BOX </line1>
<line2> SUBURB </line2>
<country> SOUTH AFRICA </country>
<postalCode> 1320 </postalCode>
<undeliverable> 0 </undeliverable>
</address>
</addresses>
</contactDetails>
<defaultPayPoint isn="726" userID="010Q09" timestamp="2014-05-15T14:29:08+02:00" millis="700" type="BANK_ACCOUNT">
<code> C11005 </code>
<name> FIRST NAT BANK MALELANE </name>
<bankName> FIRST NATIONAL BANK </bankName>
<branchName> FIRST NAT BANK MALELANE </branchName>
<branchCode> 270952 </branchCode>
<accountNumber> 00000000064646464644 </accountNumber>
<accountHolderName> AT SURNAME </accountHolderName>
</defaultPayPoint>
</person>
</persons>
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
if ("ns".equals(prefix)) {
return "http://www.ods.co.za";
}
return null;
}
@Override
public String getPrefix(String namespaceURI) {
return null;
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
});
//Retrieves an entry
xpath.evaluate("/ns:persons/ns:person/ns:partyID", new InputSource(new StringReader(xmlResponse)));
//Retrieves an attribute
xpath.evaluate("/ns:persons/ns:person/@isn", new InputSource(new StringReader(xmlResponse)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment