xml解析方式的具体实现 --(二)

DOM解析方式:
1)技术入口: 
 org.w3c.dom包中的 “Document接口”----dom树中的document对象
 原来在js-dom中,docment对象是已经存在的,我们直接用就行。
 现在在application-dom中,我们需要自己写代码去获取它。---调用sun公司开发的xml解析工具(包)来实现
 
2)sun公司开发的xml解析工具(包):  javax.xml.parsers 
 
3)dom解析方式的基本套路: 
    调用javax.xml.parsers包中的相应类生成
    org.w3c.dom.Document接口,
        然后就可以进行dom操作了。
 *
 *
 //解析标记中的内容时,建议使用Element中的getElementByTagName()
 */

/**********************请注意导包时要导入org.w3c.dom.中的包*********************/

public class DomDemo {

    //需求: 把users.xml中的第一个user元素中的name值输出来
    @Test
    public void hello() throws Exception{
        //1 获取DocumentBuilderFactory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //2 获取DocumentBuilder
        DocumentBuilder db = dbf.newDocumentBuilder();
        //3 获取org.w3c.dom.Document接口--document对象
        Document document = db.parse("./xml/users.xml");
        
        //4 利用document进行dom操作 //xml文档的根元素是document的第一个孩子
        Node root = document.getFirstChild(); //<users>节点
        String nm = root.getNodeName();
        System.out.println("nm="+nm); //users
        
        
        ///////////通过Node获取子节点集合的方式,不建议使用,因为存在#text即空白符节点//////////////
        NodeList nodeList = root.getChildNodes();//返回<users>节点中的所有子节点
        System.out.println(nodeList.item(0).getNodeName());//#text---空白符
        System.out.println(nodeList.item(1).getNodeName());
        System.out.println(nodeList.item(2).getNodeName());
        
        System.out.println("------------------------");
        
        
        ///////////※※※建议通过Element获取子节点,可避开空白符的干扰,
        //因为Element接口中有getElementsByTagName(String name)方法可以调用,而Node中没有/////////////////////////
        Element eUsers = (Element) root;
        NodeList nodeList2 = eUsers.getElementsByTagName("user"); //获取<users>中的所有<user>子节点---不包括空白节点
        System.out.println(nodeList2.item(0).getNodeName());//#text---空白符
        System.out.println(nodeList2.item(1).getNodeName());
        //nodeList2中的最后一个元素
        System.out.println(nodeList2.item( nodeList2.getLength()-1).getNodeName());
        
        //把users.xml中的第一个user元素中的name值输出来
        Element eUser = (Element) nodeList2.item(0);
        Node eName = eUser.getElementsByTagName("name").item(0);
        System.out.println(eName.getTextContent());//Jack
    }

//反模式: java-dom中最好不用getElementById()的方式来获取节点,因为该方式需要使用Schema,非常麻烦!有兴趣可以参看
    @Test
    public void getElementByIdDemo() throws Exception{
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document dom = db.parse( new File("./xml/users.xml") );
        
        Element eNode = dom.getElementById("A002");
        System.out.println(eNode); //null
    }

}

猜你喜欢

转载自blog.csdn.net/qq_35307947/article/details/81942247
今日推荐