java 获得xml自定义属性

xmlKit

import com.jfinal.weixin.sdk.utils.IOUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.namespace.QName;
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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

public class XMLKit{
    private final XPath path;
    private final Document doc;

    private XMLKit(InputSource inputSource) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbf = getDocumentBuilderFactory();
        dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
        dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        dbf.setXIncludeAware(false);
        dbf.setExpandEntityReferences(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        this.doc = db.parse(inputSource);
        this.path = getXPathFactory().newXPath();
    }

    private static XMLKit create(InputSource inputSource) {
        try {
            return new XMLKit(inputSource);
        } catch (ParserConfigurationException var2) {
            throw new RuntimeException(var2);
        } catch (SAXException var3) {
            throw new RuntimeException(var3);
        } catch (IOException var4) {
            throw new RuntimeException(var4);
        }
    }

    public static XMLKit of(InputStream is) {
        InputSource inputSource = new InputSource(is);
        return create(inputSource);
    }

    public static XMLKit of(String xmlStr) {
        StringReader sr = new StringReader(xmlStr.trim());
        InputSource inputSource = new InputSource(sr);
        XMLKit xmlHelper = create(inputSource);
        IOUtils.closeQuietly(sr);
        return xmlHelper;
    }

    private Object evalXPath(String expression, Object item, QName returnType) {
        item = null == item ? this.doc : item;

        try {
            return this.path.evaluate(expression, item, returnType);
        } catch (XPathExpressionException var5) {
            throw new RuntimeException(var5);
        }
    }

    public String getString(String expression) {
        return (String)this.evalXPath(expression, (Object)null, XPathConstants.STRING);
    }

    public Boolean getBoolean(String expression) {
        return (Boolean)this.evalXPath(expression, (Object)null, XPathConstants.BOOLEAN);
    }

    public Number getNumber(String expression) {
        return (Number)this.evalXPath(expression, (Object)null, XPathConstants.NUMBER);
    }

    public Node getNode(String expression) {
        return (Node)this.evalXPath(expression, (Object)null, XPathConstants.NODE);
    }

    public NodeList getNodeList(String expression) {
        return (NodeList)this.evalXPath(expression, (Object)null, XPathConstants.NODESET);
    }

    public String getString(Object node, String expression) {
        return (String)this.evalXPath(expression, node, XPathConstants.STRING);
    }

    public Boolean getBoolean(Object node, String expression) {
        return (Boolean)this.evalXPath(expression, node, XPathConstants.BOOLEAN);
    }

    public Number getNumber(Object node, String expression) {
        return (Number)this.evalXPath(expression, node, XPathConstants.NUMBER);
    }

    public Node getNode(Object node, String expression) {
        return (Node)this.evalXPath(expression, node, XPathConstants.NODE);
    }

    public NodeList getNodeList(Object node, String expression) {
        return (NodeList)this.evalXPath(expression, node, XPathConstants.NODESET);
    }

    public Map<String, String> toMap() {
        Element root = this.doc.getDocumentElement();
        Map<String, String> params = new HashMap();
        NodeList list = root.getChildNodes();

        for(int i = 0; i < list.getLength(); ++i) {
            Node node = list.item(i);
            if (node instanceof Element) {
                params.put(node.getNodeName(), node.getTextContent());
            }
        }

        return params;
    }

    private static DocumentBuilderFactory getDocumentBuilderFactory() {
        return XMLKit.XMLKitHolder.documentBuilderFactory;
    }

    private static XPathFactory getXPathFactory() {
        return XMLKit.XMLKitHolder.xPathFactory;
    }

    private static class XMLKitHolder {
        private static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        private static XPathFactory xPathFactory = XPathFactory.newInstance();

        private XMLKitHolder() {
        }
    }

    /**
     * 获得根节点属性
     * @param attr
     * @return
     */
    public Map getRootTagAttr(String[] attr) {
        Map retrunMap = new HashMap();
        Element root = this.doc.getDocumentElement();
        for (int i = 0; i < attr.length; i++) {
            retrunMap.put(attr[i],root.getAttribute(attr[i]));
        }
        return  retrunMap;
    }
}
IOUtils
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;

public abstract class IOUtils {
    private static final int DEFAULT_BUFFER_SIZE = 4096;

    public IOUtils() {
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException var2) {
            ;
        }

    }

    public static String toString(InputStream input) throws IOException {
        return toString(input, Charsets.UTF_8);
    }

    public static String toString(InputStream input, Charset charset) throws IOException {
        InputStreamReader in = new InputStreamReader(input, charset);
        StringBuffer out = new StringBuffer();
        char[] c = new char[4096];

        int n;
        while((n = in.read(c)) != -1) {
            out.append(new String(c, 0, n));
        }

        closeQuietly(in);
        closeQuietly(input);
        return out.toString();
    }

    public static void toFile(InputStream input, File file) throws IOException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = false;
        byte[] buffer = new byte[4096];

        int bytesRead;
        while((bytesRead = input.read(buffer, 0, 4096)) != -1) {
            os.write(buffer, 0, bytesRead);
        }

        closeQuietly(os);
        closeQuietly(input);
    }
}

调用

            XMLKit xmlHelper = XMLKit.of(xml);
            return xmlHelper.getRootTagAttr(tags);

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励