dom4j

package com.px.dom4j;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.XMLReader;

public class test1 {
public static void main(String[] args) {
SAXReader sr=new SAXReader();
try {

Element elt=DocumentHelper.createElement("student");//创建一个student 元素
Element name=DocumentHelper.createElement("name");
Element age=DocumentHelper.createElement("age");
name.setText("张五");
age.setText("20");
elt.addAttribute("sn","03");

Document doc=sr.read(new File("students.xml"));
//添加
Element root=doc.getRootElement();

elt.add(name);
elt.add(age);
root.add(elt);
//删除元素
//root.remove(elt);
Element stu=root.element("student");
String val=stu.attribute("sn").getText();
if(val.equals("01")){
root.remove(stu);
}

//修改值
root.element("student").element("name").setText("张九");
OutputFormat outformat=new OutputFormat();
outformat.setEncoding("GB2312");
    outformat.setNewlines(true);
    outformat.setIndent(true);
    outformat.setTrimText(true);
XMLWriter xmlwriter =new XMLWriter(System.out,outformat);
xmlwriter.write(doc);

} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

出现的效果:
<?xml version="1.0" encoding="GB2312"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>

<students>
  <student sn="02">
    <name>张九</name>
    <age>20</age>
  </student>
  <student sn="03">
    <name>张五</name>
    <age>20</age>
  </student>
</students>



你可能感兴趣的:(xml,XSL)