虽然您需要代码来读取和解析来自某些源和类的 xml 以管理和操作 xml 信息集,但答案归结为以下 XPath 表达式:
//Placemark/name[./text()='east am']
这个表达式选择 ...
-
name 元素,正在...
- ...
Placemark 元素的子元素...
- ...文档中的任何位置,...
- ...
name 元素的文本内容为east am。
替代方案
//Placemark/name[string(.)='east am']
有关string(.) 和./text() 之间区别的完整讨论,请参阅this SO answer。
基本上,一方面,如果 xml 节点的文本内容由多个文本节点表示,./text() 会失败。 AFAIK 这个决定是由解析器做出的,你无法指导这个选择。
另一方面,如果目标name 节点属于复杂类型,即。可能有带有自己文本内容的子元素,您需要指定目标元素本身及其后代的所有文本片段的串联。
代码
此代码是一个独立示例,用于从作为示例给出的 xml 文件中收集由给定 xpath 表达式引用的节点的表示。
此代码源自this SO answer,所有归功于其作者,与我无关。
请注意,您的 xml 摘录不是有效的独立 xml 文件,因为它缺少单个根元素。如果文件还没有合成根,则将其添加到文件中(xpath 表达式可以使用任何一种方式)。
文件名是xpath.java 和test.51320827.xml。用 java 1.8.0_45 测试;
// https://stackoverflow.com/questions/51320827/how-can-i-retrieve-the-child-node-using-xpath-java
//
// code taken from: https://stackoverflow.com/a/47280397
//
//
import java.lang.*;
import java.io.*;
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class xpath {
public static void main(String[] args) {
String xpathExpression = "//Placemark/name[./text()='east am']";
// Read file
Document doc = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File( "test.51320827.xml" );
FileInputStream stream = new FileInputStream( file );
doc = builder.parse( stream );
} catch (SAXException | IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
// get from XPath
try {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression compile = xpath.compile(xpathExpression);
NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);
displayNodeList(nodeList);
} catch (XPathExpressionException e) {
e.printStackTrace();
}
System.out.println("\n===== ***** =====");
}
static void displayNodeList( NodeList nodeList ) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String NodeName = node.getNodeName();
NodeList childNodes = node.getChildNodes();
if ( childNodes.getLength() > 1 ) {
for (int j = 0; j < childNodes.getLength(); j++) {
Node child = childNodes.item(j);
short nodeType = child.getNodeType();
if ( nodeType == 1 ) {
System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
}
}
} else {
System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
}
}
}
}