一、DOM读取
import ***;
public class ReadXML {
public static void main(String[] args) {
try {
//DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("languages.xml"));
Element root = document.getDocumentElement();
System.out.println("cat="+root.getAttribute("cat"));
NodeList list = root.getElementsByTagName("lan");
for (int i = 0; i < list.getLength(); i++) {
Element lan = (Element) list.item(i);
System.out.println("---------------");
System.out.println("id="+lan.getAttribute("id"));
NodeList clist = lan.getChildNodes();
for (int j = 0; j < clist.getLength(); j++) {
Node c = clist.item(j);
if (c instanceof Element) {//这一行的作用是将元素键的回车换行等不可见的元素如#text去掉
System.out.println(c.getNodeName()+"="+c.getTextContent());
}
}
}
} catch (**){...}
}
xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<Languages cat="it">
<lan id="1">
<name>Java</name>
<ide>Eclipse</ide>
</lan>
<lan id="2">
<name>Swift</name>
<ide>Xcode</ide>
</lan>
<lan id="3">
<name>C#</name>
<ide>Visual Studio</ide>
</lan>
</Languages>
二、DOM创建XML
//DOM
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element root = document.createElement("Languages");
root.setAttribute("cat", "it");
Element lan1 = document.createElement("lan");
lan1.setAttribute("id", "1");
Element name1 = document.createElement("name");
name1.setTextContent("Java");
Element ide1 = document.createElement("ide");
ide1.setTextContent("Eclipse");
lan1.appendChild(name1);
lan1.appendChild(ide1);
Element lan2 = document.createElement("lan");
lan2.setAttribute("id", "2");
Element name2 = document.createElement("name");
name2.setTextContent("Swift");
Element ide2 = document.createElement("ide");
ide2.setTextContent("XCode");
lan2.appendChild(name2);
lan2.appendChild(ide2);
Element lan3 = document.createElement("lan");
lan3.setAttribute("id", "3");
Element name3 = document.createElement("name");
name3.setTextContent("C#");
Element ide3 = document.createElement("ide");
ide3.setTextContent("Visual Studio");
lan3.appendChild(name3);
lan3.appendChild(ide3);
root.appendChild(lan1);
root.appendChild(lan2);
root.appendChild(lan3);
document.appendChild(root);
//-------------
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
System.out.println(writer.toString());
transformer.transform(new DOMSource(document), new StreamResult(new File("newxml.xml")));