【问题标题】:Parsing attribute in XML with DOM parser使用 DOM 解析器解析 XML 中的属性
【发布时间】:2012-02-26 07:32:56
【问题描述】:

我目前正在解析XML,但我不太清楚如何解析“消息”的“状态”属性:

<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();
            }
}       

谁能指导我如何做到这一点?

提前致谢。

【问题讨论】:

    标签: java xml dom xml-parsing


    【解决方案1】:

    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

    【讨论】:

    • 谢谢你的回复,能解释一下aNode的属性吗?
    • @JavaCake aNode 指的是您要为其检索属性的节点。在您的情况下,它是指“消息”元素的节点。
    • 您介意根据我的代码给出实现示例吗?我无法准确确定它是如何完成的。
    • @JavaCake 我编辑了我的代码。我假设“消息”是您的 xml 的根元素。如果是,那么它将起作用。试试看,让我知道。您可以在 DOM 中使用 doc.getDocumentElement() 获取根元素
    • @JavaCake 我刚刚意识到“消息”不是根元素。您需要在 fstElmnt 上调用该方法。我编辑了我的代码
    【解决方案2】:

    我一直在使用Apache Xerces 来解析 DOM。但这是可怕的任务。如果可以,请查看jsoup

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

    node.attr("status")
    

    【讨论】:

    • 我很遗憾我没有这样做,但不幸的是我现在不能改变太多,应用程序很大。
    猜你喜欢
    • 1970-01-01
    • 2013-01-31
    • 2013-07-18
    • 2020-07-26
    • 2013-12-24
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多