- import java.io.FileOutputStream;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.output.XMLOutputter;
- public class XMLDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- System.out.println("生成xml文件");
- new XMLDemo().createXML();
- }
- public void createXML() {
- // 创建根节点
- Element root = new Element("list");
- // 根节点添加到文档中
- Document document = new Document(root);
- for (int i = 0; i < 5; i++) {
- Element elements = new Element("user");
- // 给user 节点添加id 属性
- elements.setAttribute("id", "" + i);
- // 给 user 节点添加子节点并赋值;
- // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui
- // 替换成表中记录值;
- elements.addContent(new Element("name").setText("xuehui"));
- elements.addContent(new Element("age").setText("28"));
- elements.addContent(new Element("sex").setText("Male"));
- // 给父节点list添加user子节点;
- root.addContent(elements);
- }
- XMLOutputter XMLOut = new XMLOutputter();
- // 输出 user.xml 文件;
- try {
- XMLOut.output(document, new FileOutputStream("user.xml"));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- ---------------------解析xml文件
- import java.io.FileInputStream;
- 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 XMLParse {
- /**
- * @param args
- */
- public static void main(String[] args) {
- new XMLParse().XMLParse();;
- }
- public void XMLParse(){
- //这里不给绝对路径也行,直接user.xml,但是前提是不管你写什么路径你必须都有xml文件
- String xmlpath="D:\\EXTJS\\extdemo\\user.xml";
- //使用JDOM首先要指定使用什么解析器,可以给参数false、true
- SAXBuilder builder=new SAXBuilder();
- try {
- //得到Document,我们以后要进行的所有操作都是对这个Document操作的:
- Document doc=builder.build(new FileInputStream(xmlpath));
- //得到根元素
- Element users=doc.getRootElement();
- //得到元素(节点)的集合:
- List list=users.getChildren();
- //得到根节点下面的第一个用户
- Element user = (Element)list.get(0);
- //为这个用户添加第一个属性 email
- Attribute params = new Attribute("email","zzz@163.com");
- user.setAttribute(params);
- //为这个用户添加一个子节点
- user.addContent(new Element("class").setText("S305"));
- //得到这个用户的name元素的值
- Element name = user.getChild("name");
- //给这个元素重新赋值
- name.setText("zhangsan");
- System.out.println(user.getChildText("name"));
- //保存Document的修改到XML文件中:
- XMLOutputter outputter=new XMLOutputter();
- outputter.output(doc,new FileOutputStream(xmlpath));
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
Java解析xml以及创建xml文件
最新推荐文章于 2023-10-23 07:32:15 发布