天天看點

使用 JAXP 查詢某一個節點|學習筆記

開發者學堂課程【XML 入門:使用 JAXP 查詢某一個節點】學習筆記,與課程緊密聯系,讓使用者快速學習知識。

課程位址:

https://developer.aliyun.com/learning/course/37/detail/851

使用 JAXP 查詢某一個節點

步驟:1、建立解析器工廠

2、根據解析器工廠建立解析器

3、解析 xml,傳回 document

4、得到所有 name 元素

5、使用傳回集合,裡面方法 item,下标擷取具體的元素 NodeList.item(下标):集合下标從 0 開始

6、得到具體的值,使用 getTextContent 方法

public class TestJaxp {

public static void main(String[] args) throws Exception {

/ / selectAll();

selectSin();

}

//查詢 xml 中第一個 name 元素的值

​​

public static void selectSin( ) throws Exception {

//建立解析器工廠

DocumentBuilderFactory builderFactory

=

DocumentBuilderFactory

.

newInstance

();

//建立解析器

DocDocumentBuilder builder

=

 builderFactory

.

newDocumentBuilder

();

//解析 xml,得到 document

Document document = builder.parse( "src/ person.xml");

//得到所有的 name 元素

NodeList list = document.getElementsByTagName( "name");

//使用下标 得到第一個元素

Node name1 = list.item(0);

//得到 name 裡面的具體的值

String s1= name1.getTextContent();

System.out.printn(s1);

}