XML入门:使用JAXP查询某一个节点

查询xml中第一个元素值

xml还是使用上一节的 person.xml

package cn.xtnotes.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;

/**
 * 
 * @author Administrator
 *
 */
public class Sele {
	public static void main(String[] args) throws Exception {
	
		selectSin();
	}
    //查询xml中第一个name值
	public static void selectSin() throws Exception {
		/*
		 * 1.创建解析器工程
		 * 2.根据解析工厂创建解析器
		 * 3.解析xml,返回document
		 * 4.得到所以的的name值
		 * 5.使用返回集合,里面的方法item,下标获取具体的元素
		 * 6.得到具体的值,使用geTesxtContent方法
		 */
		//创建解析器工厂
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		//创建解析器
		DocumentBuilder builder = builderFactory.newDocumentBuilder();
		//解析xml,得到document
		Document document = builder.parse("src/person.xml");
		//得到所有的name元素
		NodeList list = document.getElementsByTagName("name");
		//使用下标得到第一个元素
		Node name1 = list.item(0);   // item(n)  第n个元素
		//得到name里面的具体值
		String  s1=name1.getTextContent();
		System.out.println(s1);
	}
	}
}

阅读剩余
THE END