企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
课件代码:https://gitee.com/flymini/codes02/tree/master/xml_/com-learn-xml01 **** **1. 解析xml文件** ```xml <students> <student order="001" id="zhangsan"> <name>张三</name> <age>25</age> 张三,你好! </student> <student order="002"> <name>李四</name> <age>28</age> 李四,你好! </student> </students> ``` ```java @Test public void read() throws DocumentException { String xmlFile = this.getClass().getResource("/student.xml").getPath(); File file = new File(xmlFile); SAXReader reader = new SAXReader(); Document document = reader.read(file); //获取xml文档的根元素 Element root = document.getRootElement(); //获取根元素下的所有<student>元素 List<Element> list = root.elements("student"); Iterator<Element> iterator = list.iterator(); while (iterator.hasNext()) { Element element = iterator.next(); System.out.println(element.element("name").getText()); System.out.println(element.attributeValue("order")); System.out.println(); } //张三 //001 // //李四 //002 } ``` <br/> **2. 将XML文档存入另一个新的文档** ```java @Test public void write() throws IOException, DocumentException { String xmlFile = this.getClass().getResource("/student.xml").getPath(); File file = new File(xmlFile); SAXReader reader = new SAXReader(); Document document = reader.read(file); /* 自定义xml样式 OutputFormat format = new OutputFormat(); format.setIndentSize(2); //行缩进 format.setNewlines(true); //一个结点为一行 format.setTrimText(true); //去除空格 format.setPadText(true); format.setNewLineAfterDeclaration(false); //放置xml文件中第二行为空白行 */ Writer writer = new FileWriter("e:/student03.xml"); OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(writer, format); xmlWriter.write(document); xmlWriter.close(); } ```