我想解析一个 xml 文件,我正在使用 Java 和 xpath 评估。
我想用 xpath 表达式输出当前的节点兄弟而不使用 getNextSibling() 函数,这可能吗?
例如,如果我们读取 name 元素,我想添加 xpath 表达式 =“./address”,以便在不使用 getNextSibling()/ 的情况下输出“name”的兄弟。
xml文件如下:
<root>
<name>
<address>
<profession>
</root>
我的代码如下:
package dom_stack4;
import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class Dom_stack4 {
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
// TODO code application logic here
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("root.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("/root/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(" Name is : " + nodes.item(i).getNodeValue());
/* IS that possible here ?? */
/* ./address/text() => outputs the current's node sibling */
expr = xpath.compile("./address/text()");
Object result1 = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;
for (int j = 0; j < nodes1.getLength(); j++) {
System.out.println(" ---------------- " + nodes1.item(j).getNodeValue());
}
}
}
}
提前致谢