首页 > 代码库 > java 解析 xml 文件
java 解析 xml 文件
学习下解析 xml 文件,这里用到了 org.dom4j 这个 jar 包,使用 eclipse 没有这个包的小伙伴可以去下个 jar 包,然后复制到项目路径下,右键 jar 包后 build path,add build path 即可。
来引入相关依赖:
import java.io.File; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader;
注意会抛错,这里 throws 一下:
public static void main (String[] args) throws Exception{ }
初始化变量:
SAXReader reader = new SAXReader(); File file = new File("***.xml"); Document document = reader.read(file); Element root = document.getRootElement(); List<Element> childElements = root.elements();
循环进行打印:
for (Element child : childElements) { List<Attribute> attributeList = child.attributes(); for(Attribute attr : attributeList) { System.out.println(attr.getName() + ": " + attr.getValue()); } List<Element> elementList = child.elements(); for (Element ele : elementList) { System.out.println(ele.getName() + ": " + ele.getText()); } }
还是很 easy 的嗷~
xml文件中结构类似这样:
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="001"> <title>Harry Potter</title> <author>J K. Rowling</author> </book> <book id="002"> <title>Learning XML</title> <author>Erik T. Ray</author> </book> </books>
java 解析 xml 文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。