我正在尝试使用XPath库读取XML文件的行。到目前为止,我已经能够读取正在处理的文档的每个节点,但是我不知道如何访问该节点的特定属性。
为了更好的理解,我将给出一个示例以及到目前为止开发的代码:
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
我想做的是获取value属性的值,在该示例中,所有节点都包含文本“ Spanish”。
使用以下代码,我阅读了每一行,但是我不知道如何使用Java XPath库访问属性的值:
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
String xPathExpression = "//string";
Document documento = null;
NodeList nodos = null;
try {
// Carga del documento xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
documento = builder.parse(new File("./src/TestResults/xmlFile.lang"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
// Preparación de xpath
XPath xpath = XPathFactory.newInstance().newXPath();
// Consultas
nodos = (NodeList) xpath.evaluate(xPathExpression, documento, XPathConstants.NODESET);
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (int i=0;i<nodos.getLength();i++){
System.out.println("********* ITER " + i + " *********");
System.out.println(nodos.item(i).getNodeName());
System.out.println(nodos.item(i).getNodeValue());
System.out.println(nodos.item(i).getAttributes());
System.out.println("**************************");
}
}
尚不清楚您要实现什么,但是如果您想要'value'属性的值,则XPath表达式可以是:
//string/@value
其中'@'是attribute
轴的简写。也可以写成
//string/attribute::value