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其它的APIpublic 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); }}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦