xml六种解析方式

/*src/p1.xml文档*/

<?xml version = "1.0" encoding = "utf-8">
<Person>
    <p1>
        <name>张三</name>
        <age>23</age>
    </p1>
    <p1>
        <name>李四</name>
        <age>24</age>
    </p1>
</person>


/*(-)jaxp解析器*/

/*(1)jaxp的document解析方式*/

public static void main(String []args){
    //1.创建解析器工厂
    //2.创建解析器
    //3.获取Document
    //4.获取name节点集合
    //5.获取name值
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse("src/p1.xml");
    NodeList list = d.getElementsByTagName("name");
    for(int i = 0;i < list.getLength();i++){
        Node name = list.item(i);
        String s = name.getTextContent();
        syso(s);
    }
}

 


/*(2)jaxp的sax解析方式*///该方式只能实现查询操作
 

 1   //1.创建jaxp的sax解析器工厂
 2     //2.创建解析器
 3     //3.调用parse方法
 4     //4.重写DefaultHandler类
 5     SAXParserFactory spf = SAXParserFactory.newInstance();
 6     SAXParser sp = spf.newSAXParser();
 7     sp.parse("p1.xml",new dh());
 8 
 9     class dh extends DefaultHandler{
10             public void startElement(String uri, String localName, String qName,
11             Attributes attributes) throws SAXException {
12         System.out.print("<"+qName+">");
13     }
14 
15     @Override
16     public void endElement(String uri, String localName, String qName)
17             throws SAXException {
18         System.out.print("<"+qName+"/>");
19     }
20 
21     @Override
22     public void characters(char[] ch, int start, int length)
23             throws SAXException {
24             System.out.print(new String(ch,start,length));
25     }
26     }

 
/*dom4j解析器*/

public static void main(String[] args){//实现xml的查询操作
    //1.创建dom4j解析器
    //2.获取document
    //3.获取根元素
    //4.获取p1集合
    //5.获取name元素
    //6.获取name值
    SAXReader sr = new SAXReader();
    Document d = sr.read("p1.xml");
    Element root = d.getRootElement("p1");
    List<Element> list = root.elements("name");
    for(Element e:list){
        Element name = e.element();
        String s = name.getText();
        syso(s);
    }

}

 




posted @ 2021-04-26 15:03  EugeniaGao  阅读(134)  评论(0编辑  收藏  举报