jaxp查询结点 eg://获取name的值 // person.xml ?xml version="1.0" encoding="UTF-8"?person p1 namezhangsan/name age20/age /p1 p1 namelisi/name age30/age /p1/person //TestJaxp.java package cn.xry.jaxp;import java.io.IOException;import j
jaxp查询结点
eg://获取name的值
// person.xml
<?xml version="1.0" encoding="UTF-8"?> <person> <p1> <name>zhangsan</name> <age>20</age> </p1> <p1> <name>lisi</name> <age>30</age> </p1> </person>
//TestJaxp.java
package cn.xry.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.NodeList; import org.xml.sax.SAXException; /* * 实现jaxp操作xml * * */ public class TestJaxp { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { //查询所有name元素的值 /* *1.创建解析器工厂 *2.根据解析器工厂创建解析器 * 3.解析xml返回document * * 4.得到所有name元素 * */ //创建解析器工厂 DocumentBuilderFactory builderFactoty = DocumentBuilderFactory.newInstance(); //创建解析器 DocumentBuilder builder = builderFactoty.newDocumentBuilder(); //解析xml返回document Document document = builder.parse("src/person.xml"); //得到name元素 NodeList nodeLists = document.getElementsByTagName("name"); for(int i=0;i!=nodeLists.getLength();i++) { System.out.println(nodeLists.item(i).getTextContent()); // 注意此处链式调用 } } }