利用SAX api分解XML数据 实例代码 实用小功能
SAX API 解析XML文件 实例, 动态加载图片配置并展现出来
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<xml-body>
<YunDong>
<LuDi>
<QiChe>
<name>danren</name>
<classpath>/reflects.DanRen</classpath>
<picturepath>/reflect/picture/0528.jpg</picturepath>
</QiChe>
<QiChe>
<name>duoren</name>
<classpath>/reflects.DuoRen</classpath>
<picturepath>/reflect/picture/0529.jpg</picturepath>
</QiChe>
<QiChe>
<name>erren</name>
<classpath>/reflects.ShuangRen</classpath>
<picturepath>/reflect/picture/0530.jpg</picturepath>
</QiChe>
</LuDi>
</YunDong>
</xml-body>
工具类:
public void xmlDecode() throws ParserConfigurationException, SAXException, IOException{
String uri = this.getClass().getResource("/com/java/functions/xmldecode/YunDong.xml").getPath();
System.out.println(uri);
//单例模式 的xml 构建器的创建方式 ;
DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();
//xml 构造器 builder
DocumentBuilder DBbuilder = DBfactory.newDocumentBuilder();
//利用xml文件创建 文档的 方式,parse 方法 的应用;
Document doc = DBbuilder.parse(uri);
//获取xml文件中的 所有节点的集合 nodeList
NodeList nodeList = doc.getElementsByTagName("QiChe");
for (int i = 0; i < nodeList.getLength(); i++) {
//获取所有的同一节点的元素List , 定位到 第 I 个 元素 ,
//获取 第 I 个元素的 第一个 孩子节点 , 获取 第一个孩子节点的 值 ;
String id = doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
String name = doc.getElementsByTagName("classpath").item(i).getFirstChild().getNodeValue();
String salary = doc.getElementsByTagName("picturepath").item(i).getFirstChild().getNodeValue();
System.out.println(id + " " + name +" " + salary);
}
}
/**
* 解析XML animal.xml
* 可以为程序提供配置性的操作
*/
public static void main(String[] args) {
XmlDecode xd = new XmlDecode();
try {
xd.xmlDecode();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
如有疑问 请留言 欢迎提供建议
评论已有 0 条