All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tools.xml.XmlUtil Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
package tools.xml;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: zhengyu
 * @date: 2019/1/10
 * @protocol: http 或 thrift
 * @apiName: /uri 或 服务名.接口名
 * @description:
 */
public class XmlUtil {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtil.class);

    private Document document = null;
    private Element rootElement = null;

    /*默认构造函数率先执行*/
    private XmlUtil(){
        logger.info("感谢:{}","您正在使用XmlUtil工具类。");
    }

    public static XmlUtil getNewInstance(){
        return new XmlUtil();
    }

    private XmlUtil(String filePath){
        this.document = loadXML(filePath);
        this.rootElement = this.document == null ? null : this.document.getRootElement();
    }

    public static XmlUtil getXMLInstance(String filePath){
        return new XmlUtil(filePath);
    }

    private Document loadXML(String filename) {
        Document document = null;
        try {
            SAXReader saxReader = new SAXReader();
            document = saxReader.read(new File(filename)); // 读取XML文件,获得document对象
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return document;
    }

    public void loadFromUrl(URL url) {
        try {
            SAXReader saxReader = new SAXReader();
            this.document = saxReader.read(url); // 读取XML文件,获得document对象
            this.rootElement = this.document.getRootElement();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void loadFromResource(String resource){
        logger.info("loadFromResource has been called.");
        // 读取文件字节流
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(resource);
        SAXReader saxReader = new SAXReader();
        try {
            this.document = saxReader.read(inputStream); // 读取String,获得document对象
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        this.rootElement = this.document.getRootElement();
    }

    public void loadFromString(String string, String charsetName) {
        InputStream is = null;
        try {
            if (charsetName!=null && !"".contentEquals(charsetName))
                is = new ByteArrayInputStream(string.getBytes(charsetName));
            else
                is = new ByteArrayInputStream(string.getBytes());
            SAXReader saxReader = new SAXReader();
            this.document = saxReader.read(is); // 读取String,获得document对象
            this.rootElement = this.document.getRootElement();
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Element getRootElement(){
        return this.rootElement;
    }

    public Document getDocument(){
        return this.document;
    }

    /*************** 读取XML文件 ***************/

    public List getAllSubElements(Element element){
        return element.elements();
    }

    public List getSubElementsByName(Element nodeElement, String eleName){
        if (this.containsElement(nodeElement, eleName))
            return nodeElement.elements(eleName);
        else {
            logger.error("<"+nodeElement.getName()+"> 的子元素中没有 <"+eleName+">");
            return null;
        }
    }


    public Element getElementFromRoot(String path){
        Element element = getElementByPath(this.rootElement, path);
        logger.info("返回绝对路径为:"+element.getUniquePath()+" 的Element对象。");
        return element;
    }

    public Element getElementByPath(Element element, String path){
        String[] pathArray = path.split("\\.");
        int indexStart,indexEnd,count = 0;
        Element currEle = element;
        if (pathArray.length > 1){
            String eleName = "";
            for (int i=1; i elementList = currentEle.elements().stream()
                .filter(element -> targetEleName.contentEquals(element.getName()))
                .collect(Collectors.toList());
        if (elementList != null && elementList.size() > 0)
            return true;
        else
            return false;
    }

    public boolean containsElements(Element currentEle, String... targetEleNameArray){
        boolean flag = true;
        List yesList = new ArrayList<>();
        List noList = new ArrayList<>();
        List subEleNameList = currentEle.elements().stream()
                .map(Element :: getName)
                .collect(Collectors.toList());
        if (subEleNameList != null && subEleNameList.size() > 0){
            for (int i=0; i 标签 包含的子标签有:"+yesList.toString());
            logger.info("<"+currentEle.getName() + "> 标签 不包含的子标签有:"+noList.toString());
        }else {
            flag = false;
            logger.info("<"+currentEle.getName() + "> 标签 不包含任何子标签。");
        }
        return flag;
    }


    public String getAttributeValue(Element currentElement, String attributeName){
        return currentElement.attributeValue(attributeName);
    }

    public boolean containsAttribute(Element currentElement, String attributeName){
        return currentElement.attribute(attributeName) == null? false : true;
    }

    public boolean containsAttributes(Element currentElement, String...attributeArray){
        boolean flag = true;
        List yesList = new ArrayList<>();
        List noList = new ArrayList<>();
        for (String attrName : attributeArray){
            if (currentElement.attribute(attrName) != null){
                yesList.add(attrName);
            }else {
                noList.add(attrName);
                flag = false;
            }
        }
        logger.info("包含的属性有:"+yesList.toString());
        logger.info("不含的属性有:"+noList.toString());
        return flag;
    }

    public Map getAttributeInfo(Element currentElement){
        Map attributeMap = new HashMap<>();
        Iterator iterator = currentElement.attributeIterator();
        Attribute tempAttr = null;
        while (iterator.hasNext()){
            tempAttr = iterator.next();
            attributeMap.put(tempAttr.getQualifiedName(),tempAttr.getValue());
        }
        return attributeMap;
    }


    /*************** 创建 XML 文件 *****************/

    public boolean createXMLFile(String rootElementName, String xmlFilePath) throws FileNotFoundException, UnsupportedEncodingException, DocumentException {
        this.document = DocumentHelper.createDocument();
        this.rootElement = this.document.addElement(rootElementName);
        this.rootElement.setText("");
        return this.saveXMLFile(xmlFilePath);
    }

    public boolean parseStringToXML(String stringValue, String xmlFilePath){
        boolean flag = true;
        try {
            this.document = DocumentHelper.parseText(stringValue);
            this.rootElement = this.document.getRootElement();
            flag = this.saveXMLFile(xmlFilePath);
        } catch (DocumentException e) {
            e.printStackTrace();
            flag = false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            flag = false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }


    /*************** 修改 XML 文件 *****************/

    public Element addElementUnderRoot(String elementName){
        return this.document.addElement(elementName);
    }

    public Element addElement(Element currentElement, String elementName, String elementValue){
        Element newElement = currentElement.addElement(elementName);
        newElement.setText(elementValue);
        return newElement;
    }

    public Element updateElementText(Element targetElement, String newText){
        targetElement.setText(newText);
        return targetElement;
    }

    public Element addAttribute(Element currentElement, String attributeName, String attributeValue){
        return currentElement.addAttribute(attributeName,attributeValue);
    }

    public void modifyAttribute(Element currentElement, String attributeName, String attributeValue){
        currentElement.attribute(attributeName).setValue(attributeValue);
    }



    /*************** 保存 XML 文件 *****************/
    public boolean saveXMLFile(String destXmlFilePath) throws FileNotFoundException, UnsupportedEncodingException {
        return this.wirteToXMLFile(this.document, destXmlFilePath);
    }

    private boolean wirteToXMLFile(Document document, String destXmlFilePath) throws FileNotFoundException, UnsupportedEncodingException {
        boolean flag = true;
        FileOutputStream fos = new FileOutputStream(destXmlFilePath);
        OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");

        OutputFormat format = OutputFormat.createPrettyPrint();

        format.setEncoding("UTF-8");

        XMLWriter writer = new XMLWriter(osw,format);
        try {
            writer.write(document);
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        }finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    public String formatXmlDocument(String charsetName) throws IOException {
        // 格式化输出格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        if (charsetName != null && !"".contentEquals(charsetName))
            format.setEncoding(charsetName);
        StringWriter writer = new StringWriter();
        // 格式化输出流
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        // 将document写入到输出流
        xmlWriter.write(this.document);
        xmlWriter.close();
        return writer.toString();
    }

    public String formatXmlString(String unformatedXmlWithSpace){
        String result = "";
        if(unformatedXmlWithSpace.contains("> ")){
            result = unformatedXmlWithSpace.replace("> ",">\n ");
            int posLast = result.lastIndexOf("




© 2015 - 2024 Weber Informatics LLC | Privacy Policy