parse xml document using dom method
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了parse xml document using dom method相关的知识,希望对你有一定的参考价值。
the bookstore.xml:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<bookname>weicheng</bookname>
<author>qianzhongshu</author>
</book>
<book id="2" value="2_2">
<bookname>yidoudewunv</bookname>
<author>chuangduankangcheng</author>
</book>
<book id="3" class="3_3">
<bookname>a song of ice and fire</bookname>
<author>george martin</author>
</book>
</bookstore>
package com.user;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Bookstore {
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
// TODO Auto-generated method stub
NodeList nodeList=DocumentBuilderFactory.newInstance().
newDocumentBuilder().parse("src/com/user/Bookstore.xml").getElementsByTagName("book");
System.out.println("There are "+nodeList.getLength()+" books");
for(int i=0;i<nodeList.getLength();i++){
System.out.println("======"+(i+1)+" ");
Node node=nodeList.item(i);
NamedNodeMap nameNodeMap=node.getAttributes();
NodeList childnodeList=node.getChildNodes();
for(int j=0;j<nameNodeMap.getLength();j++){
Node nodeMap=nameNodeMap.item(j);
System.out.println(nodeMap.getNodeName()+": "+nodeMap.getNodeValue());
}
for (int k=0;k<childnodeList.getLength();k++){
Node childNode=childnodeList.item(k);
if (childNode.getNodeType()==Node.ELEMENT_NODE){
System.out.println(childNode.getNodeName()+": "+childNode.getFirstChild().getNodeValue());
}
}
System.out.println(" "+(i+1)+"------");
}
}
}
run the java program:
以上是关于parse xml document using dom method的主要内容,如果未能解决你的问题,请参考以下文章
异常IOException parsing XML document from class path resource [xxx.xml]
BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource
[翻译][Ruby教程]Nokogiri - 解析HTML/XML文档 / Parsing an HTML/XML Document
vmware.c:1226: error: ‘XML_PARSE_HUGE’ undeclared (first use in this function)
IOException parsing XML document from class path resource [WebRoot/WEB-INF/applicationContext.xml];
Spring出现Unexpected exception parsing XML document from class path resource [applicationBeans.xml]; n