java操作xml——JDom使用詳解
JDom是一個開源項目,它基於樹形結構,利用純JAVA的技術對XML文檔實現解析、產生、序列化以及多種操作。 JDom簡介
JDom直接為JAVA變成服務。它利用更為有力的java語言的諸多特性(方法重載、集合概念以及映射),把SAX和DOM的功能有效地結合起來。在使用設計上儘可能地隱藏原來使用xml過程中的複雜性。利用JDom處理xml文檔是一件輕鬆簡單的事。
JDOM 在2000年的春天被Brett McLaughlin和Jason Hunter開發出來,以彌補DOM及SAX在實際應用當中的不足之處。
這些不足之處主要在於SAX沒有文檔修改、隨機訪問以及輸出的功能,而對於DOM來說,java程式員在使用時不是很方便。
DOM的缺點主要是來自於DOM是一個介面定義語言(IDL),它的任務實在不同語言實現統一。並不是為java特別設計的。 JDOM包概覽
JDOM是由以下幾個包組成
| 包名 |
解釋 |
| org.jdom |
包含了所有的xml文檔要素的java類 |
| org.jdom.adapters |
包含了與dom適配的java類 |
| org.jdom.filter |
包含了xml文檔的過濾器類 |
| org.jdom.input |
包含了讀取xml文檔的類 |
| org.jdom.output |
包含了寫入xml文檔的類 |
| org.jdom.transform |
包含了將jdom xml文檔介面轉換為其它xml文檔的介面 |
| org.jdom.xpath |
包含了對xml文檔xpath操作的類 |
案例之通過jdom產生xml
package xmlTest;import java.io.FileOutputStream;import org.jdom.Document;import org.jdom.Element;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;public class GenerateJdom{ public static void main(String[] args) throws Exeception{ Document doc = new Document() ; Element root = new Element("root") ; doc.addContent(root) ; Element name = new Element("name") ; root.addContent(name) ; root.setAttribute("author","yanzhelee").setAttribute("url","http://www.csdn.com") ; name.addContent("yanzhelee"); XMLOutputter out = new XMLOutputter() ; Format format = Format.getPrettyFormat(); format.setIndent(" "); out.setFormat(format); out.output(doc, new FileOutputStream("jdom.xml")) ; }}
下面是產生的xml
<?xml version="1.0" encoding="UTF-8"?><root author="yanzhelee" url="http://www.csdn.com"> <name>yanzhelee</name></root>
通過jdom解析xml文檔
package xmlTest;/** * @author CIACs */import java.io.File;import java.io.FileOutputStream;import java.util.List;import org.jdom.Attribute;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder;import org.jdom.output.XMLOutputter;public class ParseJdom{ public static void main(String[] args) throws Exeception{ // 通過SAXBuilder解析xml SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(new File("jdom.xml")); Element root = doc.getRootElement(); System.out.println(root.getName()); String name = root.getChild("name").getText(); System.out.println("name: "+name); List attrs = root.getAttributes(); for(int i = 0; i < attrs.size();i++) { String attrName; String attrValue; Attribute attr = (Attribute)attrs.get(i); attrName = attr.getName(); attrValue = attr.getValue(); System.out.println(attrName+":"+attrValue); } //刪除屬性url,並儲存到jdom2.xml root.removeAttribute("url"); XMLOutputter out = new XMLOutputter(); out.output(doc, new FileOutputStream("jdom2.xml")); }}
maven依賴
<dependency> <groupId>org.jdom</groupId> <artifactId>jdom</artifactId> <version>1.1</version></dependency>
參考博文
https://www.cnblogs.com/zhi-hao/p/4016363.html