首先声明,博主是一名菜鸟,现在在实习。由于工作需要,需要学习一下xml的解析,今天先写一下自己学习的过程以及心得。
进入正题,先上eclipse的目录结构:
再上xml文件 (test2.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!-- note 是test2.xml的第一个节点 -->
<!-- to、from、heading、body、是note的子节点 -->
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
xml是w3cschool官方给的示例
由于刚开始不太熟悉,以为note节点和to、from、heading、body节点是同一级的,导致走了很多弯路,正确的说明在xml文件注释,接着也会在代码中进行说明。
再上一下java文件(TestXmlParse.java)
package com.edu2act.www;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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;
public class TestXmlParse {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// TODO Auto-generated method stub
//
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("test2.xml");
//根据节点的名字获取结点列表
NodeList list = document.getElementsByTagName("note");
//获取当前的结点
Node node = list.item(0);
System.out.println(node); //结果:[note: null]
//获取当前结点的子结点
NodeList childs = node.getChildNodes();
for (int i = 0; i < childs.getLength(); i++) {
//判断节点的类型 ①
if(childs.item(i) instanceof Element){
System.out.println(childs.item(i).getNodeName());
System.out.println(childs.item(i).getTextContent());
}
}
}
}
以上就是java文件的代码
重点说一下①处的判断逻辑,刚开始没有if语句的时候,每次控制台都会打印#text的字样,很烦人,经过百度,发现xml文件中回车也会算作一个节点,所以会在控制台打印#text.
以下截图是程序的运行结果:
有什么不妥的地方,谢谢指正。 菜鸟的第一个博客文章。