1.读取XML
2.写入XML
3.新建XML
4.创建构造XML
创建新的xml文档:
1 /构造一个XML解析器 并且创建新的文档/ 2 1 Document document = null; 3 2 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 4 3 try { 5 4 DocumentBuilder builder = factory.newDocumentBuilder(); 6 5 document = builder.newDocument();//创建一个新的XML文件 7 6 //document = builder.parse(fileName);//解析已存在的XML文件 8 7 } catch (ParserConfigurationException e) { 9 8 e.printStackTrace(); 10 9 }
将内存中的xml输出到文件上面:
1 //将内存中的xml,输出到文件上面 2 Transformer tf = null; 3 TransformerFactory tff = TransformerFactory.newInstance(); 4 try { 5 tf = tff.newTransformer(); 6 tf.transform(new DOMSource(document), new StreamResult("src/test.xml")); 7 8 } catch (TransformerConfigurationException e) { 9 e.printStackTrace(); 10 } catch (TransformerException e) { 11 e.printStackTrace(); 12 }
构建xml:
1 Element root = document.createElement("root");//创建根目录 2 3 Element student = document.createElement("student"); 4 5 student.setAttribute("name", "xiaoming");//设置student 的属性值 6 7 /*创建student的子元素*/ 8 Element id = document.createElement("id"); 9 Element sex = document.createElement("sex"); 10 Element age = document.createElement("age"); 11 12 /*设置元素的文本*/ 13 id.setTextContent("0001"); 14 sex.setTextContent("man"); 15 age.setTextContent("18"); 16 17 /*将子元素添加到父元素(student)中*/ 18 student.appendChild(id); 19 student.appendChild(sex); 20 student.appendChild(age); 21 22 root.appendChild(student);//将元素(节点)student 添加到根目录(root)中去 23 document.appendChild(root);//将根目录添加到文档中去
输出结果:
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?> 2 <root> 3 <student name="xiaoming"> 4 <id>0001</id> 5 <sex>man</sex> 6 <age>18</age> 7 </student> 8 </root>
获取XML中的数据
1 <?xml version="1.0" encoding="UTF-8" standalone="no"?><root> 2 <student name="xiaoming"> 3 <id>0001</id> 4 <sex>man</sex> 5 <age>18</age> 6 </student> 7 <student name="xiaozhu"> 8 <id>0002</id> 9 <sex>man</sex> 10 <age>20</age> 11 </student> 12 <student name="xiaohong"> 13 <id>0003</id> 14 <sex>female</sex> 15 <age>15</age> 16 </student> 17 </root>
对XML进行查找操作
1 //获取student中属性name=xiaoming的所有信息 2 NodeList list_st =document.getElementsByTagName("student"); 3 /*遍历所有student的元素*/ 4 for(int i=0;i<list_st.getLength();i++) 5 { 6 Node n =list_st.item(i); 7 8 Element student= (Element)n;//必须强转为元素才能获取到设置的属性,节点获取不了属性 9 10 /*找出student中属性xiaoming的节点*/ 11 if(student.getAttribute("name").equals("xiaoming")) 12 { 13 /*获取所有标签中的文本信息*/ 14 String id = student.getElementsByTagName("id").item(0).getTextContent(); 15 String sex = student.getElementsByTagName("sex").item(0).getTextContent(); 16 String age = student.getElementsByTagName("age").item(0).getTextContent(); 17 18 System.out.println("id:"+id); 19 System.out.println("sex:"+sex); 20 System.out.println("age:"+age); 21 /*输出: 22 * id:0001 23 * sex:man 24 * age:18 25 */ 26 } 27 }
时间: 2024-10-14 12:15:57