基于JDOM生成解析XML過程解析
JDOM是一個開源項目,它基于樹型結(jié)構(gòu),利用純JAVA的技術(shù)對XML文檔實現(xiàn)解析、生成、序列化以及多種操作。
JDOM 直接為JAVA編程服務(wù)。它利用更為強有力的JAVA語言的諸多特性(方法重載、集合概念以及映射),把SAX和DOM的功能有效地結(jié)合起來。
Jdom是用Java語言讀、寫、操作XML的新API函數(shù)。Jason Hunter 和 Brett McLaughlin公開發(fā)布了它的1.0版本。在直覺、簡單和高效的前提下,這些API函數(shù)被最大限度的優(yōu)化。在接下來的篇幅里將介紹怎么用Jdom去讀寫一個已經(jīng)存在的XML文檔。
到官方網(wǎng)站下載JDOM包http://www.jdom.org/
注意的是,版本1和版本2的類路徑已經(jīng)變更,如果你是更新使用版本2,則需要重新編譯你的代碼
package com.test;
import java.io.FileOutputStream;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* @說明 JDom生成解析XML
* @author cuisuqiang
* @version 1.0
* @since
*/
@SuppressWarnings("unchecked")
public class JDomDemo {
public static void main(String[] args) {
String file = "C:\\p.xml"; // 文件存放位置
JDomDemo dj = new JDomDemo();
dj.createXml(file);
dj.parserXml(file);
}
/**
* 生成XML
* @param filePath 文件路徑
*/
public void createXml(String fileName) {
Element root = new Element("persons");
Document document = new Document(root);
Element person = new Element("person");
root.addContent(person);
Element name = new Element("name");
name.setText("java小強");
person.addContent(name);
Element sex = new Element("sex");
sex.setText("man");
person.addContent(sex);
Element age = new Element("age");
age.setText("23");
person.addContent(age);
XMLOutputter XMLOut = new XMLOutputter();
try {
Format f = Format.getPrettyFormat();
f.setEncoding("UTF-8");//default=UTF-8
XMLOut.setFormat(f);
XMLOut.output(document, new FileOutputStream(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析XML
* @param filePath 文件路徑
*/
public void parserXml(String fileName) {
try {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(fileName);
Element root = document.getRootElement();
List persons = root.getChildren("person");
for (int i = 0; i < persons.size(); i++) {
Element person = (Element) persons.get(i);
List pros = person.getChildren();
for (int j = 0; j < pros.size(); j++) {
Element element = (Element) pros.get(j);
System.out.println(element.getName() + ":" + element.getValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot+EHcache 實現(xiàn)文章瀏覽量的緩存和超時更新
這篇文章主要介紹了springboot+EHcache 實現(xiàn)文章瀏覽量的緩存和超時更新,問題描述和解決思路給大家介紹的非常詳細,需要的朋友可以參考下2017-04-04
Spring Boot結(jié)合IDEA自帶Maven插件如何快速切換profile
IDEA是目前 Java 開發(fā)者中使用最多的開發(fā)工具,它有著簡約的設(shè)計風(fēng)格,強大的集成工具,便利的快捷鍵,這篇文章主要介紹了Spring Boot結(jié)合IDEA自帶Maven插件快速切換profile,需要的朋友可以參考下2023-03-03
Java從ftp服務(wù)器上傳與下載文件的實現(xiàn)
這篇文章主要給大家介紹了關(guān)于Java從ftp服務(wù)器上傳與下載文件的實現(xiàn)方法,最近項目中需要實現(xiàn)將文件先存放到ftp上,需要的時候再從ftp上下載,做的過程中碰到了問題,所以這里總結(jié)下,需要的朋友可以參考下2023-08-08

