xml这类文件格式在很多时候都是很合适我们用来存取数据的,所以利用程序来生成xml文件和解析xml文件就显得比较重要了。在dom中是把每个元素都看作是1个节点Node的,所有页面上的属性、元素等都是继承自Node的,所以当获得到的是1个Node,而你知道它实际的类型并需要使用的时候便可能会需要进行类型转换了。
Element root = document.getDocumentElement();//获得根节点
下面是代码:
生成xml:
-
public void geneXmlByDom() throws Exception {
-
-
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-
-
DocumentBuilder db = factory.newDocumentBuilder();
-
-
Document document = db.newDocument();
-
-
Element rootElement = document.createElement("Persons");
-
for (int i=0;i<5;i++) {
-
-
Element person = document.createElement("person");
-
-
person.setAttribute("id", "id_"+i);
-
Element name = document.createElement("name");
-
-
name.setTextContent("name_"+i);
-
Element address = document.createElement("address");
-
address.setTextContent("address_"+i);
-
Element email = document.createElement("email");
-
email.setTextContent("email_"+i);
-
person.appendChild(name);
-
person.appendChild(address);
-
person.appendChild(email);
-
-
rootElement.appendChild(person);
-
}
-
-
document.appendChild(rootElement);
-
-
TransformerFactory transformerFactory = TransformerFactory.newInstance();
-
-
Transformer transformer = transformerFactory.newTransformer();
-
-
Source xmlSource = new DOMSource(document);
-
-
Result outputTarget = new StreamResult(new File("persons.xml"));
-
-
transformer.transform(xmlSource, outputTarget);
-
}
生成的xml文件是这个模样
-
<?xml version="1.0" encoding="UTF⑻" standalone="no"?>
-
<Persons>
-
<person id="id_0">
-
<name>name_0</name>
-
<address>address_0</address>
-
<email>email_0</email>
-
</person>
-
<person id="id_1">
-
<name>name_1</name>
-
<address>address_1</address>
-
<email>email_1</email>
-
</person>
-
<person id="id_2">
-
<name>name_2</name>
-
<address>address_2</address>
-
<email>email_2</email>
-
</person>
-
------分隔线----------------------------
------分隔线----------------------------