Java 怎么通过xpath设置xml-cdata

2019年7月29日20:54:15Java 怎么通过xpath设置xml-cdata已关闭评论 622 2089字阅读6分57秒

1.简介

Java 怎么通过xpath设置xml-cdata?——请看下文。

2.示例代码

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

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    
    public static void setCData(Document doc, String nodeXpath, String data) {
        CDATASection cdata = doc.createCDATASection(data);
        Node node = findNodeByXpath(doc, nodeXpath);
        if (node != null) {
            if (node.getTextContent() != null) { 
                node.setTextContent(null);
            }
            node.appendChild(cdata);
        }
    }
    public static Node findNodeByXpath(Document doc, String xpath) {
        NodeList nodelist = findNodeListByXpath(doc, xpath);
        if (nodelist.getLength() > 0) {
            return nodelist.item(0);
        }
        return null;
    }
    public static NodeList findNodeListByXpath(Document doc, String xpath) {
        XPathFactory pathFactory = XPathFactory.newInstance();
        
        XPath x_path = pathFactory.newXPath();
        
        Object obj = null;
        try {
            XPathExpression pathExpression = x_path.compile(xpath);
            obj = pathExpression.evaluate(doc, XPathConstants.NODESET);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("Error while xpath search");
        }
        NodeList nodelist = (NodeList) obj;

        return nodelist;
    }
    public static List<Node> findNodeListByXpath(Document doc,
            String xpath, NodeType nodeType) {
        XPathFactory pathFactory = XPathFactory.newInstance();
        
        XPath x_path = pathFactory.newXPath();
        
        Object obj = null;
        try {
            XPathExpression pathExpression = x_path.compile(xpath);
            obj = pathExpression.evaluate(doc, XPathConstants.NODESET);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("Error while xpath search");
        }
        NodeList nodelist = (NodeList) obj;

        List<Node> nlist = new ArrayList<Node>();
        for (int i = 0; i < nodelist.getLength(); i++) {
            Node n = nodelist.item(i);
            if (isNodeTypeMatches(n, nodeType)) {
                nlist.add(n);
            }
        }

        return nlist;
    }
    public static boolean isNodeTypeMatches(Node node, NodeType nodeType) {
        return ((int) node.getNodeType()) == nodeType.getValue();
    }
}

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