How to get xml attribute values ​​using Document builder factory

How do I get the attribute values ​​using the following code I am getting; as output for msg. I want to print MSID, type, CHID, SPOS, type, PPOS values. Anyone can fix this problem.

String xml1="<message MSID='20' type='2635'>"
        +"<che CHID='501' SPOS='2'>"
        +"<pds type='S'>"
        +"<position PPOS='S01'/>"
        +"</pds>"
        +"</che>"
        +"</message>";

InputSource source = new InputSource(new StringReader(xml1));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String msg = xpath.evaluate("/message/che/CHID", document);
String status = xpath.evaluate("/pds/position/PPOS", document);

System.out.println("msg=" + msg + ";" + "status=" + status);

      

+3


source to share


2 answers


You need to use @

in your XPath for the attribute and also your path specifier for the second element is wrong:

String msg = xpath.evaluate("/message/che/@CHID", document);
String status = xpath.evaluate("/message/che/pds/position/@PPOS", document);

      



With these changes, I get the output:

msg=501;status=S01

      

0


source


You can use Document.getDocumentElement()

to get the root element and Element.getElementsByTagName()

to get the children:



Document document = db.parse(source);

Element docEl = document.getDocumentElement(); // This is <message>

String msid = docEl.getAttribute("MSID");
String type = docEl.getAttribute("type");

Element position = (Element) docEl.getElementsByTagName("position").item(0);
String ppos = position.getAttribute("PPOS");

System.out.println(msid); // Prints "20"
System.out.println(type); // Prints "2635"
System.out.println(ppos); // Prints "S01"

      

0


source







All Articles