Free Man
Free Man

Reputation: 195

XML attribute Parsing

When parsing the xml, I want to retrieve the token value:

PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|

But I am currently getting the related:

Found attribute: expiry with value: 2014-10-29T22:20:00Z

xml file:

<?xml version="1.0"?>
<Inrix responseId="63448807-78d3-4ee8-90d6-a8b64abff8fc" statusText="" statusId="0"     createdDate="2014-10-29T21:21:55Z" versionNumber="5.4" copyright="Copyright INRIX Inc." docType="GetSecurityToken">
<AuthResponse>
<AuthToken expiry="2014-10-29T22:20:00Z">PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|</AuthToken>
<ServerPath>devzone.inrix.com/traffic/inrix.ashx</ServerPath>
<ServerPaths>
<ServerPath region="NA" type="API">http://na.api.inrix.com/Traffic/Inrix.ashx</ServerPath>
<ServerPath region="NA" type="TTS">http://na-rseg-tts.inrix.com/RsegTiles/tile.ashx</ServerPath>
</ServerPaths>
</AuthResponse>
</Inrix>

This is the code I wrote to parse the xml file above:

DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document document = builder.parse(new File(inputfile));
document.getDocumentElement().normalize();

NodeList AuthTokens = document.getElementsByTagName("AuthToken"); 
//NodeList AuthTokens = document.getElementsByTagName("ServerPath"); 
int num = AuthTokens.getLength();
for (int i=0; i<num;i++){
     Element node = (Element) AuthTokens.item(i);
     NamedNodeMap attributes = node.getAttributes();
     int numAttrs = attributes.getLength();
     for (int j=0; j<numAttrs;j++){
         Attr attr = (Attr) attributes.item(j);
         String attrName = attr.getNodeName();
         String attrValue = attr.getNodeValue();
         System.out.println(attr.getParentNode());
         System.out.println("Found attribute: " + attrName + " with value: " + attrValue);
     }           
 }

How do I get the correct value?

Upvotes: 1

Views: 89

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201399

I believe you want the contents of the node, not its' attributes. Change your Element to Node and then you can call Node.getTextContent()

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File(inputfile));
document.getDocumentElement().normalize();

NodeList AuthTokens = document.getElementsByTagName("AuthToken");
// NodeList AuthTokens = document.getElementsByTagName("ServerPath");
int num = AuthTokens.getLength();
for (int i = 0; i < num; i++) {
    Node node = AuthTokens.item(i);
    String token = node.getTextContent();
    System.out.println(token);
}

Output is (as requested)

PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|

Upvotes: 1

Related Questions