本文所讲的内容是有关于Java读取xml文件的相关的内容,文章大致分为三个部分,即Java类、xml文件以及最后的输出结果。
-
packagecom.java.test;
-
-
importorg.w3c.dom.*;
-
importjavax.xml.parsers.*;
-
importjava.io.*;
-
-
publicclassJavaReadXml{
-
-
-
privateDocumentdoc=null;
-
-
publicvoidinit(StringxmlFile)throwsException{
-
-
-
-
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
-
DocumentBuilderdb=dbf.newDocumentBuilder();
-
-
doc=db.parse(newFile(xmlFile));
-
}
-
-
-
publicvoidviewXML(StringxmlFile)throwsException{
-
this.init(xmlFile);
-
-
Elementelement=doc.getDocumentElement();
-
System.out.println("根元素为:"+element.getTagName());
-
-
NodeListnodeList=doc.getElementsByTagName("person");
-
System.out.println("book节点链的长度:"+nodeList.getLength());
-
-
NodefatherNode=nodeList.item(0);
-
System.out.println("父节点为:"+fatherNode.getNodeName());
-
-
-
NamedNodeMapattributes=fatherNode.getAttributes();
-
-
for(inti=0;i<attributes.getLength();i++){
-
Nodeattribute=attributes.item(i);
-
System.out.println("book的属性名为:"+attribute.getNodeName()
-
+"相对应的属性值为:"+attribute.getNodeValue());
-
}
-
-
NodeListchildNodes=fatherNode.getChildNodes();
-
System.out.println(childNodes.getLength());
-
for(intj=0;j<childNodes.getLength();j++){
-
NodechildNode=childNodes.item(j);
-
-
if(childNodeinstanceofElement){
-
-
System.out.println("子节点名为:"+childNode.getNodeName()
-
+"相对应的值为"+childNode.getFirstChild().getNodeValue());
-
}
-
}
-
-
}
-
-
publicstaticvoidmain(String[]args)throwsException{
-
JavaReadXmlparse=newJavaReadXml();
-
-
-
parse.viewXML("person.xml");
-
}
- }
一.java类
二.xml文件
- <?xmlversion="1.0"encoding="UTF-8"?>
- <book>
- <person>
- <first>wang</first>
- <last>laohu</last>
-
<age>25</age>
- <version>中国邮电出版社</version>
- </person>
- <person>
- <first>li</first>
- <last>junjia</last>
-
<age>24</age>
- <version>清华大学出版社</version>
- </person>
- </book>
三.输出结果
根元素为:book
book节点链的长度:2
父节点为:person
9
子节点名为:first相对应的值为wang
子节点名为:last相对应的值为laohu
子节点名为:age相对应的值为25
子节点名为:version相对应的值为中国邮电出版社
分享到:
相关推荐
java读写xml文件 java读写xml文件 java读写xml文件 java读写xml文件 java读写xml文件 java读写xml文件
用java读取xml文件的四种方法
文档中有代码案例,详细讲解了使用java读取xml,并附带有关于xml的dtd讲解,里面包含详细的文档和代码案例。和读取xml所需的jar。
java读取xml文件 ,程序自带jar包在mylib下,加入工程即可,工程导入可用,更具自己需要读取xml文件生成所需文件。
java 读写xml文件操作, 简单易懂
java从xml中读入数据并存入到sqlserver2005数据库中
java读取XML文件内容的四种方法[归类].pdf
java读写xml文件的例子,供参考
利用Java下的IO读取或写入xml及word,txt文件,且能有效去除乱码(很适用,且和POI组建比,少占了很多内存),这是我根据网上很多不同的版本,整合而出的一种最易最好的IO读写文件代码;
java实现的一个读取本地xml文件的例子,进入正题: 需要的包jdom2-2.0.6.jar:下载地址,http://mvnrepository.com/artifact/org.jdom/jdom2 此例子比较简单
Java读取xml文件中oracle数据库连接,JAVA与ORACLE连接的代码.
xml文件导入到mysql数据库中,包括文件:ConnectionUtils.java,InsertDT.java,db_mysql.properties,test01.xml,需要的jar包dom4j-1.6.1.jar,mysql-connection-java-3.1.1.3-bin.jar,jaxen-1.1-beta-7.jar
通过不同的库方法读取修改xml文件。通过java实现。代码易懂
Java读取xml文件的四种方法.doc
java读取XML文件,自己写的一个小例子,很多读取的方面 都涉及到了....
java读写xml文档,有实例,dom4j.jar, jaxen.jar。