我目前正在解析XML,但我不太清楚如何解析“message”的“status”属性:
<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();
}
}
任何人都可以指导我如何做到这一点吗?
提前致谢。
答案 0 :(得分:11)
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。
答案 1 :(得分:1)