使用 DOM 解析器解析 XML 中的属性 [英] Parsing attribute in XML with DOM parser

查看:31
本文介绍了使用 DOM 解析器解析 XML 中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently parsing XML, but im not quite sure how to parse the "status" attribute of "message":

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

这是代码,我已经切断了所有不必要的内容:

Here is the code, i have cut off everything unnecessary:

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

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

Can anyone guide me how this is done?

提前致谢.

推荐答案

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

You could avoid traversing if you use XPATH to retrieve the data. Read this tutorial.

这篇关于使用 DOM 解析器解析 XML 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆