解析xml的兩種方式 ,使用jaxp查詢xml結點的例項
阿新 • • 發佈:2018-11-20
解析xml的兩種方式
使用jaxp查詢xml結點的例項
person.xml
TestJaxp.java
import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class TestJaxp { /* 查詢xml內 所有name元素的值 * * 1. 建立解析器工廠 * 2. 根據解析器工廠建立解析器 * 3. 解析xml 返回 document * 4. 獲得doucument 下 所有的 name元素 list * 5. 遍歷 list */ public static void main(String[] args) throws Exception { //建立解析器工廠 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); //建立解析器 DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); //解析 Document document = documentBuilder.parse("src/person.xml"); //得到name元素 NodeList list=document.getElementsByTagName("name"); //遍歷 for(int i=0;i<list.getLength();i++){ //得到name Node name1=list.item(i); //輸出 name 裡面的值 String s=name1.getTextContent(); System.out.println(s); } } }