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

4
我正在解析 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();
            }
}       

有人能引导我如何完成这个操作吗?

提前感谢。

2个回答

12

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


谢谢您的回复,您能解释一下属性aNode吗? - JavaCake
@JavaCake aNode是指您想要检索属性的节点。在您的情况下,它是指引用“message”元素的节点。 - Aravind Yarram
你介意根据我的代码给出实现示例吗?我无法确定它是如何完成的。 - JavaCake
@JavaCake 我编辑了我的代码。我假设 "message" 是你的 XML 的根元素。如果是的话,它应该可以工作。试一下并让我知道结果。你可以使用 DOM 中的 doc.getDocumentElement() 获取根元素。 - Aravind Yarram
@JavaCake 我刚意识到 "message" 不是根元素。你需要在 fstElmnt 上调用那个方法。我已经编辑了我的代码。 - Aravind Yarram
显示剩余3条评论

2
我一直在使用Apache Xerces解析DOM,但这是一项可怕的任务。如果可以的话,请看一下jsoup
所以,如果你的问题在Jsoup中有答案,那就是:
node.attr("status")

我很遗憾没有做到那一点,但不幸的是现在我无法改变太多,这个应用程序非常庞大。 - JavaCake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接