码迷,mamicode.com
首页 > 编程语言 > 详细

Java jaxp查询节点

时间:2016-12-12 09:46:08      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:rac   exception   src   解析xml   bsp   job   win   one   tco   

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <p1>
        <name>jobs</name>
        <age>56</age>
    </p1>
    <p1>
        <name>Alis</name>
        <age>32</age>
    </p1>
</person>
package jaxp;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


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

public class TestJaxp {
    public static void main(String[] args) {
        //创建解析器工厂
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        //创建解析器
        DocumentBuilder builder = null;
        try {
            builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //解析xml返回document
        Document document = null;
        try {
            document = builder.parse("src/person.xml");
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 得到name元素
        NodeList list = document.getElementsByTagName("name");
        for(int i = 0; i< list.getLength(); i++){
            Node node = list.item(i);
            //得到对应元素的值
            String str = node.getTextContent();
            System.out.println(str);
        }
    }
}

 

Java jaxp查询节点

标签:rac   exception   src   解析xml   bsp   job   win   one   tco   

原文地址:http://www.cnblogs.com/lantu1989/p/6163219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!