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

tools.xml.DOMXMLReader Maven / Gradle / Ivy

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.IOException;

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

    private String xmlContent;
    private String charset;
    private Element element;
    private Element appHead;

    public DOMXMLReader(String xmlConent, String charset) throws ParserConfigurationException, IOException, SAXException {
        this.xmlContent = xmlConent;
        this.charset = charset;
        this.init();
    }

    private void init() throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new InputSource(new ByteArrayInputStream(xmlContent.getBytes(charset))));
        Element root = document.getDocumentElement();
        this.element = (Element) root.getElementsByTagName("SERVICE_BODY").item(0);
        this.appHead = (Element) root.getElementsByTagName("SERVICE_HEADER").item(0);
    }


    public String getValueByAppHead(String tagName){
        String value = "";
        Node node = appHead.getElementsByTagName(tagName).item(0);
        if (node != null){
            value = node.getTextContent();
        }
        return value;
    }


    public String getValueByTagName(String tagName){
        String value = "";
        if (this.element != null
                && this.element.getElementsByTagName(tagName) != null
                && this.element.getElementsByTagName(tagName).getLength()>0){
            Node node = this.element.getElementsByTagName(tagName).item(0);
            if (node != null){
                value = node.getTextContent();
            }
        }
        if (value == null || value.length()==0 || "null".equals(value)){
            value = "";
        }
        return value;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy