版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38230811/article/details/84281171
解析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);
}
}
}