Java修炼之路——读取XML文件


这次来跟记录下java下如何操作xml文件。其实用过python去爬虫的话,那么应该很容易上手。java中有一个库dom4j就跟python中的lxml类似。

这里要重点强调下,在使用dom4j库的时候,其实它还有一个依赖包,就是jaxen。不添加的可是会报错的。(dom4j和jaxen的下载链接都整理好了在底部)

 

这里主要就是讲讲怎么用dom4j来读取的xml文件(可以直接从网络上加载,或者本地)

//这个是官网上copy的,直接从加载文件

public class Foo { public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; } } //这个是加载本地的xml
public static Document parse(String path){ SAXReader reader = new SAXReader(); Document document = null; try { document = reader.read(“你的xml文件路径”); } catch (DocumentException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } return document; }

现在得到的这个Document类,就是一个存储着根据xml解析好的文本了,你想怎么折腾就从这儿开始吧。

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>George</to>
<from>John</from>
<heading name="test">Reminder</heading>
<body>Don't forget the meeting!</body>
<body type="test2">Don't forget the meeting2!</body>
</note>

 

现在举个小例子。xml文件在上面给出了

public static void testDom4j(Document data){ //1: 读取to里面的data
   Element lElement1 = (Element) file.selectSingleNode("/note/to");   String toValue = IElement1.getStringValue();  //dom4j中每个element就是对应的是一个node。 //2:读取heading中name的属性
   Element lElement2 = (Element) file.selectObject("/note/heading");   String headingNameValue =  IElement2.attributeValue("name") //3根据Node的属性选择,从body中选择type="test2"那个
   Element lElement3 = (Element) file.selectObject("/note/heading[@type='test2' ");   String bodValue=  IElement3.getStringValue();
}

这三种应该是比较常用的了,当然还有其他API没提到。不过都类似的啦。大家可以上官网看看

 

就写到这儿了。有什么要补充的下次再加吧。(主要太懒,撤~~)

om4j:

https://dom4j.github.io/(更新)

jaxen的下载地址:
http://maven.ibiblio.org/maven2/jaxen/jaxen/1.1.1/


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM