package com.xml.stu;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
public class TestCreateXml {
private void createXml() throws FileNotFoundException, IOException {
/**
* 构建XML文档节点名
*/
Element root = new Element("resume");
Element name = new Element("name");
Element job = new Element("job");
Element gender = new Element("gender");
/**
* 给指定的节点添加参数属性
*/
Attribute attr = new Attribute("startAge","20");
name.setAttribute(attr);
/**
* 构建DOM结构,往根节点root里添加子元素。
*/
root.addContent(name);
root.addContent(job);
root.addContent(gender);
/**
* 往节点里添加值,addContent(container):可以添加值和节点
* setText(string text):只能添加值
*/
name.addContent("朱元幛");
job.setText("黄帝");
gender.setText("其他");
/**
* 构建DOM节点
*/
Document doc = new Document(root);
// Format f = Format.getPrettyFormat(); //xml的完美显示格式
Format f = Format.getCompactFormat();//xml的紧凑显示格式
f.setEncoding("gbk");
//用流的方式生成xml文件 ;把DOM树从内存写到硬盘上。
XMLOutputter xmlOut = new XMLOutputter(f);
xmlOut.output(doc, new FileOutputStream("d:/2.xml"));
}
/**
* 更新XML元素内容
* @throws FileNotFoundException
* @throws JDOMException
* @throws IOException
*/
private void testUpdateXml() throws FileNotFoundException, JDOMException, IOException {
SAXBuilder sb = new SAXBuilder();
//将某一个XML文件 读入到内存当中
Document doc = sb.build(new FileInputStream("d:/2.xml"));
//对内存中的doc进行操作
//一旦得到了根元素就可以对所有XML数据进行处理。
Element root = doc.getRootElement();
Element e = root.getChild("name");
e.setText("zhujunzhang");
Format f = Format.getPrettyFormat();//xml的完美显示格式
f.setEncoding("gbk");
//用流的方式生成xml文件 ;把DOM树从内存写到硬盘上。
XMLOutputter xmlOut = new XMLOutputter(f);
xmlOut.output(doc, new FileOutputStream("d:/2.xml"));
}
/**
* XPATH对XML进行操作。
* @throws Exception
*/
private void testXPATH() throws Exception {
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(new FileInputStream("d:/2.xml"));
Element root = doc.getRootElement();//获得根元素后,就可操作所有原素了
// XPath xpath = XPath.newInstance("//name[text()='朱高煦']");
XPath xpath = XPath.newInstance("/resume/sons/name");
List list = xpath.selectNodes(root);
System.out.println("容器文体节点原素数为:"+list.size());
for (int i = 0;i < list.size();i++) {
Element e = (Element) list.get(i);
System.out.println(e.getText());
}
}
public static void main(String[] args) throws Exception {
new TestCreateXml().createXml();
// new TestCreateXml().testUpdateXml();
// new TestCreateXml().testXPATH();
}
}
项目(里面也包含了servlet练习的相关):