【196】JAVA8 用 DOM 方式的 API 解析XML文件,无需引入第三方依赖。

JAVA8 可以使用标准的 DOM 方式的 API 来编写代码解析 XML 文件,无需引入第三方依赖。下面是两个测试用的 XML 文件:

test.xml

<allData>
    <pan attr1="a" attr2="b">
        1
    pan>
    <tilt>
        2
    tilt>
    <zoom>
        3
    zoom>
    <list>
        <item>
            item0
        item>
        <item>item1item>
        <item>item2item>
    list>

    <user-list>
        <user>
            <name>
                张三
            name>
            <gender>gender>
        user>
        <user>
            <name>
                高启兰
            name>
            <gender>gender>
        user>
    user-list>
allData>

test2.xml

<allData>
    <pan attr1="a" >
        1
    pan>
    <zoom>
        3
    zoom>
    <list>
        <item>
            item0
        item>
        <item>item1item>
        <item>item2item>
    list>
allData>

负责接收所有信息的 AllDataDTO.java

package zhangchao;
import java.util.ArrayList;
import java.util.List;

public class AllDataDTO {
    private Integer pan;
    private Integer tilt;
    private Integer zoom;
    private List<String> list = new ArrayList<>();
    private String panAttr1;
    private String panAttr2;
    private List<AllDataUserDTO> userList = new ArrayList<>();
    ///
    //  setters/getters
    ///
    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("AllDataDTO{");
        sb.append("pan=").append(pan);
        sb.append(", tilt=").append(tilt);
        sb.append(", zoom=").append(zoom);
        sb.append(", list=").append(list);
        sb.append(", panAttr1='").append(panAttr1).append('\'');
        sb.append(", panAttr2='").append(panAttr2).append('\'');
        sb.append(", userList=").append(userList);
        sb.append('}');
        return sb.toString();
    }
    public List<AllDataUserDTO> getUserList() {
        return userList;
    }
    public void setUserList(List<AllDataUserDTO> userList) {
        this.userList = userList;
    }
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public String getPanAttr1() {
        return panAttr1;
    }
    public void setPanAttr1(String panAttr1) {
        this.panAttr1 = panAttr1;
    }

    public String getPanAttr2() {
        return panAttr2;
    }
    public void setPanAttr2(String panAttr2) {
        this.panAttr2 = panAttr2;
    }
    public Integer getPan() {
        return pan;
    }
    public void setPan(Integer pan) {
        this.pan = pan;
    }
    public Integer getTilt() {
        return tilt;
    }
    public void setTilt(Integer tilt) {
        this.tilt = tilt;
    }
    public Integer getZoom() {
        return zoom;
    }
    public void setZoom(Integer zoom) {
        this.zoom = zoom;
    }
}

负责接收用户信息的 AllDataUserDTO.java

package zhangchao;

public class AllDataUserDTO {
    private String name;
    private String gender;
    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("AllDataUserDTO{");
        sb.append("name='").append(name).append('\'');
        sb.append(", gender='").append(gender).append('\'');
        sb.append('}');
        return sb.toString();
    }
    ///
    //  setters/getters
    ///
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}

处理 XML 文件的工具类,XmlUtils.java

package zhangchao;

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

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

public class XmlUtils {
    public static AllDataDTO parseXml(String xmlFilePath) {
        File file = new File(xmlFilePath);
        if (!file.exists()) {
            return null;
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//创建一个DocumentBuilderFactory的对象
        DocumentBuilder builder;
        AllDataDTO allDataDTO = null;
        try {
            builder = factory.newDocumentBuilder();//创建一个DocumentBuilder对象
            Document doc = builder.parse("file:///" + xmlFilePath);
            Element root = doc.getDocumentElement();//获取根节点
            allDataDTO = new AllDataDTO();
            NodeList childNodes = root.getChildNodes();
            int length = childNodes.getLength();
            for (int i = 0; i < length; i++) {
                Node node = childNodes.item(i);
                String nodeName = node.getNodeName();
                if ("pan".equals(nodeName)) {
                    String content = node.getTextContent();
                    content = (content == null ? null : content.trim());
                    Integer tmp = null;
                    try {
                        tmp = Integer.parseInt(content);
                    } catch (NumberFormatException e) {}
                    allDataDTO.setPan(tmp);
                    NamedNodeMap namedNodeMap = node.getAttributes();
                    Node attr1 = namedNodeMap.getNamedItem("attr1");
                    if (attr1 != null) {
                        String attr1Cont = attr1.getTextContent();
                        attr1Cont = (attr1Cont == null ? null : attr1Cont.trim());
                        allDataDTO.setPanAttr1(attr1Cont);
                    }

                    Node attr2 = namedNodeMap.getNamedItem("attr2");
                    if (attr2 != null) {
                        String attr2Cont = attr2.getTextContent();
                        attr2Cont = (attr2Cont == null ? null : attr2Cont.trim());
                        allDataDTO.setPanAttr2(attr2Cont);
                    }

                } else if ("tilt".equals(nodeName)) {
                    String content = node.getTextContent();
                    content = (content == null ? null : content.trim());
                    Integer tmp = null;
                    try {
                        tmp = Integer.parseInt(content);
                    } catch (NumberFormatException e) {}
                    allDataDTO.setTilt(tmp);
                } else if ("zoom".equals(nodeName)) {
                    String content = node.getTextContent();
                    content = (content == null ? null : content.trim());
                    Integer tmp = null;
                    try {
                        tmp = Integer.parseInt(content);
                    } catch (NumberFormatException e) {}
                    allDataDTO.setZoom(tmp);
                } else if ("list".equals(nodeName)) {
                    NodeList itemList = node.getChildNodes();
                    int itemLength = itemList.getLength();
                    for (int j = 0; j < itemLength; j++) {
                        Node item = itemList.item(j);
                        if ("item".equals(item.getNodeName())) {
                            String content = item.getTextContent();
                            content = (content == null ? "" : content.trim());
                            allDataDTO.getList().add(content);
                        }
                    }
                } else if ("user-list".equals(nodeName)) {
                    NodeList userList = node.getChildNodes();
                    int userListLength = userList.getLength();
                    for (int j = 0; j < userListLength; j++) {
                        Node user = userList.item(j);
                        // 读取用户的属性
                        if ("user".equals(user.getNodeName())) {
                            AllDataUserDTO userDTO = new AllDataUserDTO();
                            NodeList params = user.getChildNodes();
                            int paramsLength = params.getLength();
                            for (int k = 0; k < paramsLength; k++) {
                                Node param = params.item(k);
                                String content = param.getTextContent();
                                if (content != null) {
                                    content = content.trim();
                                }
                                String paramName = param.getNodeName();
                                if ("name".equals(paramName)) {
                                    userDTO.setName(content);
                                } else if ("gender".equals(paramName)) {
                                    userDTO.setGender(content);
                                }
                            }
                            allDataDTO.getUserList().add(userDTO);
                        }
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return allDataDTO;
    }
}

用于测试效果的类 Main.java

package zhangchao;

public class Main {
    public static void main(String[] args) {
        AllDataDTO allDataDTO = XmlUtils
                .parseXml("E:\\ws\\zc\\Java8Xml\\src\\main\\resources\\TestFile\\" +
                        "test.xml");
        AllDataDTO allDataDTO2 = XmlUtils
                .parseXml("E:\\ws\\zc\\Java8Xml\\src\\main\\resources\\TestFile\\" +
                        "test2.xml");
        System.out.println(allDataDTO);
        System.out.println(allDataDTO2);
    }
}

输出结果:

AllDataDTO{pan=1, tilt=2, zoom=3, list=[item0, item1, item2], panAttr1='a', panAttr2='b', userList=[AllDataUserDTO{name='张三', gender='男'}, AllDataUserDTO{name='高启兰', gender='女'}]}
AllDataDTO{pan=1, tilt=null, zoom=3, list=[item0, item1, item2], panAttr1='a', panAttr2='null', userList=[]}

你可能感兴趣的:(JAVA,xml,java)