在重新学习了慕课网dom解析xml文件的课程后,用Java写的一个Demo示例,可以根据指定的标签列出其下的所有的内容,其中xml文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author><a>aaab</a></author>
<year>2014</year>
<price>18</price>
</book>
<book id="2">
<name>冰与火之歌2</name>
<author>作者2</author>
<year>2016</year>
<price>19</price>
</book>
</bookstore>
相应的java代码如下,此代码可以直接运行:
package Dom;
import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Created by northleaf on 16/1/26.
*/
public class DomTest {
public static void main(String[] strings){
domXML("books.xml","book");
}
private static void domXML(String fileName,String rootElement){
DocumentBuilderFactory dbf = new DocumentBuilderFactoryImpl();
StringBuilder sb = new StringBuilder();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("books.xml");
NodeList list = document.getElementsByTagName(rootElement);
//判断是否有值,无值则退出
if (null == list) {
System.out.println("there is no element for " + rootElement);
return;
}
//有值则循环处理
for (int i = 0; i < list.getLength(); i++) {
//只需要遍历Element
if(list.item(i).getNodeType()!=Node.ELEMENT_NODE) continue;
listNode(list.item(i));
System.out.println();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void listNode(Node node){
if(null==node)return;
for(int i=0;i<getParentLevel(node);i++){
System.out.print(" ");
}
System.out.print(node.getNodeName()+":");
if(hasElementChilde(node)){
for(int i=0;i<node.getChildNodes().getLength();i++){
if(node.getChildNodes().item(i).getNodeType() != Node.ELEMENT_NODE)continue;
System.out.println();
listNode(node.getChildNodes().item(i));
}
}
else{
System.out.print(node.getTextContent());
}
}
private static int getParentLevel(Node node){
int result=0;
do{
node=node.getParentNode();
result++;
}
while(null!=node&&node.getClass()!=Document.class);
return result;
}
private static boolean hasElementChilde(Node node){
if(null==node)return false;
if(node.hasChildNodes()){
for(int i=0;i<node.getChildNodes().getLength();i++){
if(node.getChildNodes().item(i).getNodeType()!=Node.ELEMENT_NODE) continue;
return true;
}
}
return false;
}
}
运行后其结果如下: