java解析xml

问题

解析如下格式的xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?><exam>
    <student examid="111" idcard="123">
        <name>张三</name>
        <location>广州</location>
        <grade>100</grade>
    </student>
    <student examid="444" idcard="333">
        <name>李四</name>
        <location>大连</location>
        <grade>97</grade>
    </student>

    <student examid="1111111" idcard="22222">
        <name>小毛</name>
        <location>广州</location>
        <grade>23.0</grade>
    </student>
    <student examid="199" idcard="300">
        <grade>80.0</grade>
        <location>广州</location>
        <name>钟源茂</name>
    </student>
</exam>

解决

根据数据,定义类对象用于存储

@Getter
@Setter
class Student{
    private String name;
    private String examid;
    private String idcart;
    private String location;
    private String grade;

    @Override
    public String toString(){
        return "姓名:" + name + ", 身份证号:" + idcart + ", 准考证号:" + examid + ", 地区:" + location + ", 成绩:" + grade;
    }
}

解析xml数据

public class JaxpSimpleDemo {
    private static Student find() throws Exception {
        Document document = getDocument();
        NodeList list = document.getElementsByTagName("student");
        for (int i = 0; i < list.getLength(); i++) {
            Element element = (Element) list.item(i);

            Student student = new Student();
            student.setExamid(element.getAttribute("examid"));
            student.setIdcart(element.getAttribute("idcard"));
            student.setName(element.getElementsByTagName("name").item(0).getTextContent());
            student.setLocation(element.getElementsByTagName("location").item(0).getTextContent());
            student.setGrade(element.getElementsByTagName("grade").item(0).getTextContent());
            System.out.println(student);
        }
        return null;
    }

    private static Document getDocument() throws ParserConfigurationException,
            IOException, org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("/Users/***/exam.xml"));
        Element e = document.getDocumentElement();
        return document;
    }

    public static void main(String[] args) throws Exception {
        find();
    }

结果

姓名:张三, 身份证号:123, 准考证号:111, 地区:广州, 成绩:100
姓名:李四, 身份证号:333, 准考证号:444, 地区:大连, 成绩:97
姓名:小毛, 身份证号:22222, 准考证号:1111111, 地区:广州, 成绩:23.0
姓名:钟源茂, 身份证号:300, 准考证号:199, 地区:广州, 成绩:80.0  

解析

<student>里面有两类数据:一是成员变量、一是标签,分别用以下获取

  • element.getAttribute("idcard")
  • element.getElementsByTagName("name").item(0).getTextContent()

拓展

增删改查

package xmlparse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class JaxpDemo {

    public static void main(String[] args) throws Exception {
        System.out.print("添加用户:a  ");
        System.out.print("删除用户:b  ");
        System.out.println("查询成绩:c");
        System.out.print("请输入操作类型:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String type = br.readLine();

        if ("a".equals(type)) {
            //添加用户
            Student student = new Student();
            System.out.print("请输入学生姓名:");
            String name = br.readLine();
            student.setName(name);
            System.out.print("请输入学生准考证号:");
            String examid = br.readLine();
            student.setExamid(examid);
            System.out.print("请输入学生身份证号:");
            String idcard = br.readLine();
            student.setIdcart(idcard);
            System.out.print("请输入学生所在地:");
            String location = br.readLine();
            student.setLocation(location);
            System.out.print("请输入学生成绩:");
            String grade = br.readLine();
            student.setGrade(grade);

            add(student);
            System.out.println("------添加数据成功------");
        } else if ("b".equals(type)) {
            //删除用户
            System.out.print("请输入删除的学生姓名:");
            String name = br.readLine();
            delete(name);
            System.out.println("------已成功删除学生信息------");
        } else if ("c".equals(type)) {
            //查询成绩
            System.out.print("请输入查询的学生准考证号:");
            String examid = br.readLine();
            Student student = find(examid);
            System.out.println("您查询的学生信息为:");
            System.out.println(student);
        } else {
            System.out.println("对不起,您的操作有误!!");
        }
    }

    private static Student find(String examid) throws Exception {

        Document document = getDocument();
        NodeList list = document.getElementsByTagName("student");
        for (int i = 0; i < list.getLength(); i++) {
            Element element = (Element) list.item(i);
            String value = element.getAttribute("examid");
            if (examid.equals(value)) {
                Student student = new Student();
                student.setExamid(examid);
                student.setIdcart(element.getAttribute("idcard"));
                student.setName(element.getElementsByTagName("name").item(0).getTextContent());
                student.setLocation(element.getElementsByTagName("location").item(0).getTextContent());
                student.setGrade(element.getElementsByTagName("grade").item(0).getTextContent());
                return student;
            }
        }
        return null;
    }

    private static void delete(String name) throws ParserConfigurationException, IOException, TransformerException, org.xml.sax.SAXException {
        Document document = getDocument();
        NodeList list = document.getElementsByTagName("name");
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getTextContent().equals(name)) {
                node.getParentNode().getParentNode().removeChild(node.getParentNode());
            }
        }
        writeXml(document);
    }

    private static void add(Student student) throws Exception {
        Document document = getDocument();

        Element studentNode = document.createElement("student");
        studentNode.setAttribute("idcard", student.getIdcart());
        studentNode.setAttribute("examid", student.getExamid());

        Node name = document.createElement("name");
        name.setTextContent(student.getName());
        Node location = document.createElement("location");
        location.setTextContent(student.getLocation());
        Node grade = document.createElement("grade");
        grade.setTextContent(student.getGrade());

        studentNode.appendChild(name);
        studentNode.appendChild(location);
        studentNode.appendChild(grade);

        Element root = document.getDocumentElement();
        root.appendChild(studentNode);

        writeXml(document);
    }

    //将内存中的数据保存到XML文件中
    private static void writeXml(Document document) throws TransformerException {

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File("src/exam.xml"));

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer trans = factory.newTransformer();
        trans.transform(source, result);
    }

    //获得操作xml文件的对象
    private static Document getDocument() throws ParserConfigurationException,
            IOException, org.xml.sax.SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//得到创建 DOM 解析器的工厂。
        DocumentBuilder builder = factory.newDocumentBuilder();//得到 DOM 解析器对象。
        Document document = builder.parse(new File("/Users/wzh94434/Code/codetest/javalearntest/src/main/java/xmlparse/exam.xml")); //得到代表整个文档的 Document 对象
        Element e = document.getDocumentElement();
        return document;
    }

}

 

posted @ 2018-10-19 20:26  jihite  阅读(13971)  评论(0编辑  收藏  举报