2014-10-30 257 views
1

當解析XML,我要檢索的令牌值:XML屬性解析

PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw| 

但我目前得到相關:

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

XML文件:

<?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> 

這是我寫的解析上面的xml文件的代碼:

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); 
    }   
} 

如何獲得正確的值?

回答

1

我相信你想要的節點的內容,而不是它的'屬性。更改ElementNode,然後你可以調用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); 
} 

輸出是(的要求)

PCWTJ87OXNnGhwzvzqvbhepi2qQM6PhMdNHn7V9UuVw|