如何使用“文档”构建器工厂获取xml属性值

时间:2014-09-16 05:40:44

标签: java xml document

如何使用以下代码获取属性值;作为msg的输出。我想打印MSID,类型,CHID,SPOS,类型,PPOS值都可以解决这个问题。

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

2 个答案:

答案 0 :(得分:0)

您需要在XPath中使用@作为属性,并且第二个元素的路径说明符也是错误的:

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

通过这些更改,我得到了输出:

msg=501;status=S01

答案 1 :(得分:0)

您可以使用Document.getDocumentElement()获取根元素,使用Element.getElementsByTagName()获取子元素:

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"