使用dom4j其它的API
阿新 • • 發佈:2018-04-16
使用dom4j其它的API
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
//使用dom4j其它的API
public class Demo4 {
public static void main(String[] args) throws Exception {
//String->XML
String text = "<root><res>這是根元素</res></root>";
Document document = DocumentHelper.parseText(text);
OutputFormat format = OutputFormat.createPrettyPrint();
OutputStream os = new FileOutputStream("src/day2/domx/stringcar.xml");
XMLWriter xmlWriter = new XMLWriter(os,format);
xmlWriter.write(document);
xmlWriter.close();
/*創建空XML文件*/
Document document = DocumentHelper.createDocument();
document.addElement("root").setText("這是根元素");
OutputFormat format = OutputFormat.createPrettyPrint();
OutputStream os = new FileOutputStream("src/day2/domx/stringcar.xml");
XMLWriter xmlWriter = new XMLWriter(os,format);
xmlWriter.write(document);
xmlWriter.close();
/*指定插入次序,默認插入到最後*/
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("src/day2/domx/stringcar.xml"));
List<Element> elementList = document.getRootElement().elements();
Element newCarElement = DocumentHelper.createElement("汽車");
newCarElement.setText("這是我的汽車");
elementList.add(1,newCarElement);
OutputFormat format = OutputFormat.createPrettyPrint();
OutputStream os = new FileOutputStream("src/day2/domx/stringcar.xml");
XMLWriter xmlWriter = new XMLWriter(os,format);
xmlWriter.write(document);
xmlWriter.close();
//XML->String
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File("src/day2/domx/stringcar.xml"));
Element rootElement = document.getRootElement();
Element firstCarElement = (Element) rootElement.elements().get(0);
String xml = firstCarElement.asXML();
System.out.println(xml);
}
}
使用dom4j其它的API