[英]How to get value with considering tag name and its attribute in XML using Java
I'm sorry, I wanna ask about how to get tag value with considering tag name and its attribute. 抱歉,我想问一下如何通过考虑标签名称及其属性来获取标签值。 I use the XML for indexing on lucene
我使用XML在Lucene上建立索引
This is the XML 这是XML
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:wb="http://www.worldbank.org">
<data>
<record>
<field name="Country or Area" key="ARB">Arab World</field>
<field name="Item" key="AG.AGR.TRAC.NO">Agricultural machinery, tractors</field>
<field name="Year">1961</field>
<field name="Value">73480</field>
</record>
</data>
</Root>
In early project, I only get the tag value with source like this: 在早期的项目中,我仅使用如下来源获得标签值:
private String getTagValue(String tag, Element e) {
NodeList nlList = e.getElementsByTagName(tag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
But now, I want considering its attribute, so I must define what tag and the attribute to get the correct value. 但是现在,我要考虑其属性,因此必须定义什么标签和属性才能获得正确的值。 Thanks for the answer
感谢您的回答
Use an xpath query for this purpose. 为此,请使用xpath查询。 First create a query similar to this (eg to obtain field nodes with a certain value):
首先创建与此类似的查询(例如,获取具有特定值的字段节点):
myQuery = xpath.compile("//field[@value=\"1234\"]");
Then populate a nodeset by running the query on the dom doc: 然后通过在dom doc上运行查询来填充节点集:
Object nodeSet = myQuery.evaluate(doc, XPathConstants.NODESET);
Change getTagValue as 将getTagValue更改为
private static String getTagValue(NodeList list, String name) {
for (int i = 0; i < list.getLength(); i++) {
Element e = (Element) list.item(i);
if (e.getAttribute("name").equals(name)) {
return e.getTextContent();
}
}
return null;
}
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new File("1.xml"));
NodeList fields = doc.getElementsByTagName("field");
String country = getTagValue(fields, "Country or Area");
String year = getTagValue(fields, "Year");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.