我有一个问题,即在xml结构中深入返回值。 首先,这是xml代码:
<?xml version="1.0" encoding="UTF-8" ?>
<log>
<published>2014-03-28T15:28:36.646Z</published>
<actor>
<objectType>person</objectType>
<id>e1b8948f-321e-78ca-d883-80500aae71b5</id>
<displayName>anonymized</displayName>
</actor>
<verb>update</verb>
<object>
<objectType>concept</objectType>
<id>a1ad6ace-c722-ffa9-f58e-b4169acdb4e3</id>
<content>time</content>
</object>
<target>
<objectType>conceptMap</objectType>
<id>4b8f69e3-2914-3a1a-454e-f4c157734bd1</id>
<displayName>my first concept map</displayName>
</target>
<generator>
<objectType>application</objectType>
<url>http://www.golabz.eu/content/go-lab-concept-mapper</url>
<id>c9933ad6-dd4a-6f71-ce84-fb1676ea3aac</id>
<displayName>ut.tools.conceptmapper</displayName>
</generator>
<provider>
<objectType>ils</objectType>
<url>http://graasp.epfl.ch/metawidget/1/b387b6f</url>
<id>10548c30-72bd-0bb3-33d1-9c748266de45</id>
<displayName>unnamed ils</displayName>
</provider>
</log>
我在Stackoverflow找到了一个方法来处理(How to retrieve element value of XML using Java?):
protected String getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeValue();
}
}
return null;
}
我的问题是我不知道如何使用该方法获取特定ID(或其他元素的值)而不使用显式预定义方法(我想传递我在方法中寻找的ID) - 本身)。
如果我使用getString("id", document.getDocumentElement)
,它只返回“e1b8948f-321e-78ca-d883-80500aae71b5”-ID。如果我想获取<object>
的子节点“a1ad6ace-c722-ffa9-f58e-b4169acdb4e3”该怎么办?
答案 0 :(得分:1)
您可以使用XPath表达式。
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpression = xPath.compile("//object/id");
// this should return one "id" node
NodeList idNodelist = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
Node idNode = idNodelist.item(0);
System.out.println(idNode.getTextContent());