<?xml version="1.0" encoding="UTF-8"?>
<phones>
<!-- 手机信息 -->
<phone id="p001">
<brand>XiaoMi</brand>
<type>XiaoMi9</type>
<price>2999</price>
</phone>
<!-- 华为 -->
<phone id="p002">
<brand>HuaWei</brand>
<type>P20</type>
<price>3000</price>
</phone>
<!-- 一加 -->
<phone id="p003">
<brand>One Plus</brand>
<type>YiJia3</type>
<price>3199</price>
</phone>
</phones>
<------------------------下面是代码Java代码块------------------------------->
package cn.kgc.demo1;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
// 注释 导包 选择 w3c
private static void getShow() {
// 查看 文件 获取所有的phone 元素 存储 list里面
NodeList list1 = parses.getElementsByTagName("phone");
//打印出 list元素 的长度 有几个打印出几个
//System.out.println(list1.getLength());
//获取所有的phone元素 存储 到 list里面 输出进行遍历
for (int i = 0; i < list1.getLength(); i++) {
Node list = list1.item(i);
// 使用 Element 强转 list元素转换成 Element
Element element = (Element)list;
// 打印获取到 element 里 id元素
String id = element.getAttribute("id");
//获取到的打印出来
System.out.println("id:"+id);
// 获取 element下的 子节点
NodeList nodeList = element.getChildNodes();
// 使用循环遍历出 nodeList的 子节点
for (int j = 0; j < nodeList.getLength(); j++) {
Node node = nodeList.item(j);
//从 Phone元素的子节点中 筛选出元素节点
if (node.getNodeType() == Node.ELEMENT_NODE) {
//使用 Elemet强转 node
Element ele = (Element)node;
//强转完成赋值给予 ele 使用ele调用获取标签名
String tagName = ele.getTagName();
//使用 ele 获取 调用 文件内容 目录
String textContent = ele.getTextContent();
//打印出 标签名 文件内容
System.out.println(tagName+":"+textContent+":");
}
} // 几个子类中间以区分线 划分开
System.out.println("---------------------");
}
}
private static void getDom() throws Exception {
// 创建解析器 工厂对象
DocumentBuilderFactory builder= DocumentBuilderFactory.newInstance();
// 解析器工厂对象 创建解析器
DocumentBuilder document = builder.newDocumentBuilder();
// 解析路径 解析文件 解析器对象解析 XML
parses = document.parse(new File("src/NewFile1.xml"));
}
public static void main(String[] args) throws Exception {
//创建俩个 方法体 有异常 抛异常
getDom();
getShow();
}
}
<--------------下面是输出结果------------------------->
id:p001
brand:XiaoMi:
type:XiaoMi9:
price:2999:
---------------------
id:p002
brand:HuaWei:
type:P20:
price:3000:
---------------------
id:p003
brand:One Plus:
type:YiJia3:
price:3199:
---------------------
//有哪里写的不对或者不通的地方,下面留言多多批评,我改进
刚接触Java XML 勿喷!!!