企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**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 ParserConfigurationException, IOException, SAXException { String xmlFile = this.getClass().getResource("/student.xml").getPath(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = new File(xmlFile); //xml文档 Document document = builder.parse(file); //所有的student节点 NodeList nodeList = document.getElementsByTagName("student"); Node node = nodeList.item(0); //节点名称:student System.out.println("节点名称:" + node.getNodeName()); //节点类型定义在接口Node中,如Node.ELEMENT_NODE //节点类型:1 System.out.println("节点类型:" + node.getNodeType()); Element element = (Element) node; //元素名:student System.out.println("元素名:" + element.getTagName()); //order属性值:001 System.out.println("order属性值:" + element.getAttribute("order")); //元素内的文本: // 张三 // 25 // 张三,你好! System.out.println("元素内的文本:" + element.getTextContent()); } ``` <br/> **2. 将XML文档存入另一个新的文档** ```java @Test public void transform() throws ParserConfigurationException, IOException, SAXException, TransformerException { String xmlFile = this.getClass().getResource("/student.xml").getPath(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File file = new File(xmlFile); //xml文档 Document document = builder.parse(file); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer transformer = tranFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); Source xmlSource = new DOMSource(document); Result result = new StreamResult("e:/student2.xml"); transformer.transform(xmlSource, result); } ```