How to get attribute values by using the following code i am getting ; as output for msg . I want to print MSID,type,CHID,SPOS,type,PPOS values can any one solve this issue .
如何通过使用以下代码获取属性值;作为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 个解决方案
#1
0
You need to use @
in your XPath for an attribute, and also your path specifier for the second element is wrong:
您需要在XPath中使用@作为属性,并且第二个元素的路径说明符也是错误的:
String msg = xpath.evaluate("/message/che/@CHID", document);
String status = xpath.evaluate("/message/che/pds/position/@PPOS", document);
With those changes, I get an output of:
通过这些更改,我得到了一个输出:
msg=501;status=S01
#2
0
You can use Document.getDocumentElement()
to get the root element and Element.getElementsByTagName()
to get child elements:
您可以使用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"
#1
0
You need to use @
in your XPath for an attribute, and also your path specifier for the second element is wrong:
您需要在XPath中使用@作为属性,并且第二个元素的路径说明符也是错误的:
String msg = xpath.evaluate("/message/che/@CHID", document);
String status = xpath.evaluate("/message/che/pds/position/@PPOS", document);
With those changes, I get an output of:
通过这些更改,我得到了一个输出:
msg=501;status=S01
#2
0
You can use Document.getDocumentElement()
to get the root element and Element.getElementsByTagName()
to get child elements:
您可以使用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"