标签:使用dom4j其它的API import java.io.File;import java.io.FileOut

时间:2022-03-14 02:26:12

标签:使用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

标签:使用dom4j其它的API