【发布时间】:2014-08-27 18:37:27
【问题描述】:
我有一个查询数据库并将结果作为 XML 返回的 servlet。我使用
在 servlet 中设置变量session.setAttribute("xml", xmlString);
如果可能的话,我如何使用 XPath 检索该属性。我需要获取它,解析它,并将值写入网页。我对 XPath 很陌生。
【问题讨论】:
我有一个查询数据库并将结果作为 XML 返回的 servlet。我使用
在 servlet 中设置变量session.setAttribute("xml", xmlString);
如果可能的话,我如何使用 XPath 检索该属性。我需要获取它,解析它,并将值写入网页。我对 XPath 很陌生。
【问题讨论】:
这是一个使用 XPath 的非常简单的示例。
您可以通过以下方式了解更多信息:https://developer.mozilla.org/en-US/docs/Using_XPath
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class XPathSample {
public static void main(String[] args) {
String simpleXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><name>Bob</name></person>";
InputSource inputSource = new InputSource(new StringReader(simpleXML));
XPath xpath = XPathFactory.newInstance().newXPath();
try {
String name = xpath.evaluate("//name", inputSource);
System.out.println(name);
} catch (XPathExpressionException e) {
System.out.println(e.getMessage());
}
}
}
【讨论】: