前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 获得xml自定义属性

java 获得xml自定义属性

作者头像
DencyCheng
发布2019-02-27 17:01:53
7310
发布2019-02-27 17:01:53
举报
文章被收录于专栏:SpringBootSpringBoot

xmlKit

代码语言:javascript
复制
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;
    }
}
代码语言:javascript
复制
IOUtils
代码语言:javascript
复制
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);
    }
}

调用

代码语言:javascript
复制
            XMLKit xmlHelper = XMLKit.of(xml);
            return xmlHelper.getRootTagAttr(tags);
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年01月28日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档