【问题标题】:Get a session variable in xpath?在 xpath 中获取会话变量?
【发布时间】:2014-08-27 18:37:27
【问题描述】:

我有一个查询数据库并将结果作为 XML 返回的 servlet。我使用

在 servlet 中设置变量
session.setAttribute("xml", xmlString);

如果可能的话,我如何使用 XPath 检索该属性。我需要获取它,解析它,并将值写入网页。我对 XPath 很陌生。

【问题讨论】:

    标签: java xml servlets xpath


    【解决方案1】:

    这是一个使用 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());
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-25
      • 2011-12-09
      • 1970-01-01
      • 2014-05-25
      • 2018-06-27
      • 2018-01-04
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      相关资源
      最近更新 更多