解析的XML属性与DOM解析器

问题描述:

我目前解析XML,但我不是很清楚如何解析“消息”的“状态”属性:解析的XML属性与DOM解析器

<message status="test"> <text>sometext</text> <msisdn>stuff</msisdn> </message> 

下面是代码,我已经切断一切都是不必要的:

NodeList nodeLst = doc.getElementsByTagName("message"); 

for (int s = 0; s < nodeLst.getLength(); s++) { 

     Node fstNode = nodeLst.item(s); 

     if (fstNode.getNodeType() == Node.ELEMENT_NODE) { 

       Element fstElmnt = (Element) fstNode; 

       NodeList numberNmElmntLst = fstElmnt 
       .getElementsByTagName("msisdn"); 
       Element numberNmElmnt = (Element) numberNmElmntLst.item(0); 
       NodeList numberNm = numberNmElmnt.getChildNodes(); 
       String phoneNumber = ((Node) numberNm.item(0)) 
       .getNodeValue().substring(2); 

       NodeList txtNmElmntLst = fstElmnt 
       .getElementsByTagName("text"); 
       Element txtNmElmnt = (Element) txtNmElmntLst.item(0); 
       NodeList txtNm = txtNmElmnt.getChildNodes(); 
       String text = ((Node) txtNm.item(0)).getNodeValue(); 

       NodeList rcvNmElmntLst = fstElmnt 
       .getElementsByTagName("received"); 
       Element rcvNmElmnt = (Element) rcvNmElmntLst.item(0); 
       NodeList rcvNm = rcvNmElmnt.getChildNodes(); 
       String recievedDate = ((Node) rcvNm.item(0)).getNodeValue(); 
      } 
}  

任何人都可以指导我如何做到这一点?

在此先感谢。

Node.getAttributes()

NamedNodeMap attributes = fstElmnt.getAttributes(); 

for (int a = 0; a < attributes.getLength(); a++) 
{ 
     Node theAttribute = attributes.item(a); 
     System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue()); 
} 

如果使用XPATH检索数据,您可以避免穿越。阅读this tutorial

+0

感谢您的回复,你能解释一下属性阳极? – JavaCake 2012-02-03 17:58:22

+0

@JavaCake aNode引用您想要为其检索属性的节点。在你的情况下,Node是指“message”元素。 – 2012-02-03 18:01:18

+0

你介意根据我的代码给出实现示例吗?我无法确切地确定它是如何完成的。 – JavaCake 2012-02-03 18:13:50

我一直在玩Apache Xerces解析DOM。但这是可怕的任务。如果可以的话,看看jsoup

所以,如果你的问题在Jsoup一个答案,那就是:

node.attr("status") 
+0

我很遗憾我没有那么做,但不幸的是我现在变化不大,应用程序非常大。 – JavaCake 2012-02-03 17:50:17