這次來跟記錄下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:
jaxen的下載地址:
http://maven.ibiblio.org/maven2/jaxen/jaxen/1.1.1/