XML属性解析

时间:2014-10-30 14:24:20

标签: java xml xml-parsing

解析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 个答案:

答案 0 :(得分:1)

我相信你想要节点的内容,而不是它的'属性。将您的Element更改为Node,然后拨打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|