XML解析 -- XMLParserUtil

本文介绍了如何使用XML解析类解析XML文件,并提取数据库配置信息,包括数据源参数、驱动名称、连接URL、用户名和密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.xml解析类

package com.ithings.util.xml;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * XML文件解析
 *
 */
public class XMLParserUtil {

    private Document document;
    private XPath xPath;
    private String filePath;
    public static final int TYPE_FILE = 0;
    public static final int TYPE_STRING = 1;

    public Document getDocument() {
        return document;
    }

    /**
     * 构造方法
     *
     * @param str 如果解析类型为文件,则改参数为文件路径,反之为XML字符串
     * @param type 解析类型
     */
    public <span style="font-family: Arial, Helvetica, sans-serif;">XMLParserUtil </span>(String str, int type) {
        this(str, type, false);
    }

    /**
     * 构造方法
     *
     * @param filePath 文件路径
     * @param validate 是否Schema验证
     */
    public XMLParserUtil(String str, int type, boolean validate) {
        //得到一个DocumentBuilderFactory实例用于生成DocumentBuilder
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //Schema验证
            if (validate) {
                //打开验证特性
                factory.setValidating(true);
                //打开对命名空间的支持
                factory.setNamespaceAware(true);
                //处理Schema的工厂
                final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
                final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
                factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
            }
            //指定由此工厂创建的解析器在解析 XML 文档时,必须删除元素内容中的空格
            factory.setIgnoringElementContentWhitespace(true);
            //从DocumentBuilderFactory中得到DocumentBuilder对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            switch (type) {
                case XMLParser.TYPE_FILE:
                    this.filePath = str;
                    document = builder.parse(new File(filePath));
                    break;
                case XMLParser.TYPE_STRING:
                    document = builder.parse(new InputSource(new StringReader(str)));
                    break;
            }
            xPath = XPathFactory.newInstance().newXPath();
        } catch (SAXException ex) {
            Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 获取节点列表
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @return 节点列表
     * @throws XPathExpressionException
     */
    public NodeList getNodeList(Object context, String expression) throws XPathExpressionException {
        return (NodeList) xPath.evaluate(expression, context, XPathConstants.NODESET);
    }

    /**
     * 获取节点
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @return
     * @throws XPathExpressionException
     */
    public Node getNode(Object context, String expression) throws XPathExpressionException {
        return (Node) xPath.evaluate(expression, context, XPathConstants.NODE);
    }

    /**
     * 获取属性值
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @param key 属性名称
     * @return 属性值
     * @throws XPathExpressionException
     */
    public String getAttributeNodeValue(Object context, String expression, String key) throws XPathExpressionException {
        Node node = this.getNode(context, expression);
        String attrNodeValue = null;
        if (null != node && node.hasAttributes()) {
            attrNodeValue = node.getAttributes().getNamedItem(key).getNodeValue();
        }
        return attrNodeValue;
    }

    /**
     * 获取String类型值
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @return
     * @throws XPathExpressionException
     */
    public String getString(Object context, String expression) throws XPathExpressionException {
        return (String) xPath.evaluate(expression, context, XPathConstants.STRING);
    }

    /**
     * 获取Number类型值(int、float、long、double、byte、short)
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @return
     * @throws XPathExpressionException
     */
    public Number getNumber(Object context, String expression) throws XPathExpressionException {
        return (Number) xPath.evaluate(expression, context, XPathConstants.NUMBER);
    }

    /**
     * 获取Boolean类型值
     *
     * @param context 上下文(Document、Element、Node)
     * @param expression XPath表达式
     * @return
     * @throws XPathExpressionException
     */
    public Boolean getBoolean(Object context, String expression) throws XPathExpressionException {
        return (Boolean) xPath.evaluate(expression, context, XPathConstants.BOOLEAN);
    }

    /**
     * 设置节点内容
     *
     * @param node 节点
     * @param content 节点内容
     * @throws TransformerException
     */
    public synchronized void setNodeTextContent(Node node, String content) throws TransformerException {
        node.setTextContent(content);
        this.updateXMLFile();
    }

    /**
     * 设置节点属性值
     *
     * @param node 节点
     * @param key 属性名
     * @param value 属性值
     * @throws TransformerException
     */
    public synchronized void setNodeAttributeValue(Node node, String key, String value) throws TransformerException {
        NamedNodeMap map = node.getAttributes();
        Node attrNode = map.getNamedItem(key);
        attrNode.setNodeValue(value);
        this.updateXMLFile();
    }

    /**
     * 更新文件
     */
    private void updateXMLFile() throws TransformerException {
        TransformerFactory tfFactory = TransformerFactory.newInstance();
        Transformer tf = tfFactory.newTransformer();
        StreamResult sResult = new StreamResult(filePath);
        DOMSource source = new DOMSource(document);
        tf.setOutputProperty(OutputKeys.VERSION, "1.0");
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        //设置缩进换行
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.transform(source, sResult);
    }
}

2.根据xml,读取其中的数据库配置

            XMLParserUtil dataSourceParse = new XMLParserUtil("d://apps.xml", XMLParser.TYPE_FILE);
            document = dataSourceParse.getDocument();
            //初始化数据源参数
            initDataSourceConfig(dataSourceParse, document);


    /**
     * 初始化数据源配置
     *
     * @throws XPathExpressionException
     */
    private void initDataSourceConfig(XMLParser dataSourceParse, Document document) throws XPathExpressionException {
        Node dataSourceNode = dataSourceParse.getNode(document, String.format(FrameConstants.EXPR_DATA_SOURCE, "MySQL"));

        String driverClassName = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_DRIVER_NAME, "MySQL"));
        String url = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_URL, "MySQL"));
        String user = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_USERNAME, "MySQL"));
        String pwd = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_PASSWORD, "MySQL"));

        String temp = url.split("//")[1];
        SystemConstants.DB_IP = temp.substring(0, temp.indexOf(":"));
        SystemConstants.DB_PORT = Integer.parseInt(temp.substring(temp.indexOf(":") + 1, temp.indexOf("/")));
        SystemConstants.DB_USER = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_USERNAME, "MySQL"));
        SystemConstants.DB_PWD = dataSourceParse.getString(dataSourceNode, String.format(FrameConstants.EXPR_JDBC_PASSWORD, "MySQL"));
        SystemConstants.DB_DATABASE = temp.substring(temp.lastIndexOf("/") + 1, temp.indexOf("?"));
        log.info("备份所需参数信息:" + SystemConstants.DB_IP + "|" + SystemConstants.DB_PORT + "|" + SystemConstants.DB_USER + "|" + SystemConstants.DB_PWD + "|" + SystemConstants.DB_DATABASE);
        System.setProperty(FrameConstants.PROPERTY_JDBC_DRIVERCLASSNAME, driverClassName);
        System.setProperty(FrameConstants.PROPERTY_JDBC_URL, url);
        System.setProperty(FrameConstants.PROPERTY_JDBC_USERNAME, user);
        System.setProperty(FrameConstants.PROPERTY_JDBC_PASSWORD, pwd);

        dataSourceNode = null;
    }

3.其他部分代码

FrameConstants

    /**
     * 数据源配置表达式
     */
    //数据源配置表达式:数据源名称
    public static final String EXPR_DATA_SOURCE = " /apps/data-source[@dialect='%s']";
    //数据源配置表达式:驱动名称
    public static final String EXPR_JDBC_DRIVER_NAME = "/apps/data-source[@dialect='%s']/driver-class-name";
    //数据源配置表达式:连接URL
    public static final String EXPR_JDBC_URL = "/apps/data-source[@dialect='%s']/url";
    //数据源配置表达式:连接用户名
    public static final String EXPR_JDBC_USERNAME = "/apps/data-source[@dialect='%s']/user";
    //数据源配置表达式:连接密码
    public static final String EXPR_JDBC_PASSWORD = "/apps/data-source[@dialect='%s']/password";

xml

<?xml version="1.0" encoding="UTF-8"?>
<apps vesion="1.0.0">
	<!-- 日志记录的优先级,通过在这里定义的级别,可以控制到应用程序中相应级别的日志信息的开关。
        -1=off,0=all,1=trace,2=debug,3=info,4=warn,5=error,6=fatal  默认(4),描述:
		off:关闭日志
		trace:跟踪日志,函数调用过程的跟踪,函数输入输出的参数跟踪
		debug:调试信息:验证功能输出的调试日志
		info:运行信息,程序运行过程中的关键信息,代表程序正在。。。
		warning:警告信息:运行警告,不影响程序运行,该异常不是关键异常
		error:错误信息,完成某个功能错误,导致功能失败
		fatal:系统错误,导致程序退出
	-->
    <log-level>4</log-level>
	<!-- 数据源 -->
    <data-source dialect="MySQL">
        <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
        <url>jdbc:mysql://localhost:3316/icloudboss?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8</url>
        <user>icloudboss</user>
        <password>Sql~!@admin3$%</password>
    </data-source>
    <data-source dialect="SQLServer">
        <driver-class-name>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class-name>
        <url>jdbc:sqlserver://localhost:1433;databaseName=iflood</url>
        <user>sa</user>
        <password>123</password>
    </data-source>
    <data-source dialect="Oracle">
        <driver-class-name>oracle.jdbc.driver.OracleDriver</driver-class-name>
        <url>jdbc:oracle:thin:@localhost:1521:orcl</url>
        <user>sa</user>
        <password>123</password>
    </data-source>
</apps>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值