Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - Parsing attribute in XML with DOM parser

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?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...