Java 怎么使用xpath表达式从XML节点获取字符串

2019年7月29日20:55:33Java 怎么使用xpath表达式从XML节点获取字符串已关闭评论 569 909字阅读3分1秒

1.简介

Java 怎么使用xpath表达式从XML节点获取字符串?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Node;

public class Main {
    static private XPath xpath;

    static public String string(Node context, String expression) {
        try {
            String result = (String) xpath.evaluate(expression, context,
                    XPathConstants.STRING);
            if (result == null || result.length() == 0)
                return null;
            else
                return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }

    static public String string(Node context, String expression,
            String defaultValue) {
        try {
            String result = (String) xpath.evaluate(expression, context,
                    XPathConstants.STRING);
            if (result == null || result.length() == 0)
                return defaultValue;
            else
                return result;
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
            throw new RuntimeException("invalid xpath expresion used");
        }
    }
}

 
继续阅读
编程十万个怎么办