使用DOM解析器解析XML中的属性

我目前正在解析XML,但我不太确定如何解析“message”的“status”属性:

 sometext stuff  

这是代码,我已经切断了一切不必要的东西:

 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检索数据,则可以避免遍历。 阅读本教程 。

我一直在玩Apache Xerces来解析DOM。 但这是一项糟糕的任务。 如果可以,请看看jsoup 。

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

 node.attr("status")