jdom是一個第三方開源項目 里面封裝了一些操作XML的接口和方法,jdom很簡單
首先下載一個jdom.jar,把它復制到項目的LIB下面
然后寫一個測試類
ReadXml .java
package test.xml;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class ReadXml {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
@SuppressWarnings("unused")
SAXBuilder sax = new SAXBuilder();
try
{
@SuppressWarnings("unused")
Document dom=sax.build("test.xml");
@SuppressWarnings("unused")
Element el=dom.getRootElement(); //得到根節點
@SuppressWarnings("unused")
List list=el.getChildren();//得到el根元素下面所有的子元素
for(int i=0;i<list.size();i++)
{
Element ee=(Element) list.get(i);
System.out.println(ee.getName());//得到ee元素的名字
System.out.println(ee.getAttributeValue("身高"));//得到ee屬性的值
System.out.println("----------");
System.out.println(ee.getValue());//得到ee節點下所有元素的值
if(ee.getChildText("小前鋒").equals("1"))
{
System.out.println(ee.getChildText("火箭"));//得到ee節點下面元素是"火箭"的值
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
就會自動生成一個test.xml的文件
<?xml version="1.0" encoding="UTF-8"?>
<籃球>
<麥迪 身高="2.02">
<小前鋒>1</小前鋒>
<火箭>62分</火箭>
</麥迪>
<科比 身高="1.98">
<得分后衛>8</得分后衛>
<!--麥迪vs科比 no.1-->
<湖人>81分</湖人>
</科比>
</籃球>
下面代碼是讀取XML中的內容
package test.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class WriteXml {
public static void main(String[] args) {
@SuppressWarnings("unused")
Document dom = new Document();
Element students = new Element("籃球"); //根節點
Element s1 = new Element("麥迪");
Element s2 = new Element("科比");
Element n1 = new Element("小前鋒");
Element n2 = new Element("得分后衛");
Element c1 = new Element("火箭");
Element c2 = new Element("湖人");
Comment cc = new Comment("麥迪vs科比 no.1"); //Comment類是注釋
n1.setText("1"); //設置n1節點元素的值
n2.setText("8");
c1.setText("62分");
c2.setText("81分");
s1.setAttribute("身高", "2.02"); //在s1節點上面加入屬性id,id的值是s01
s2.setAttribute("身高", "1.98");
s1.addContent(n1);
s1.addContent(c1);
s2.addContent(n2);
s2.addContent(cc);
s2.addContent(c2);
students.addContent(s1);//將s1節點添加到students根節點上
students.addContent(s2);
dom.addContent(students);//將根節點students添加到dom對象里面
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());//設置xml中的排版格式
try {
outputter.output(dom, new FileOutputStream("test.xml"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}