How can I create the below XML
using Java DOM
, I want to create it from scratch. Is there any way? I don't want to read it and clone it, I just want to create it by DOM
methods.
如何使用Java DOM创建以下XML,我想从头开始创建它。有什么办法吗?我不想读它并克隆它,我只想用DOM方法创建它。
Java
Example:
Java示例:
Node booking=new Node();
Node bookingID=new Node();
booking.add(bookingID);
XML
Example:
XML示例:
<tns:booking>
<tns:bookingID>115</tns:bookingID>
<tns:type>double</tns:type>
<tns:amount>1</tns:amount>
<tns:stayPeriod>
<tns:checkin>
<tns:year>2013</tns:year>
<tns:month>11</tns:month>
<tns:date>14</tns:date>
</tns:checkin>
<tns:checkout>
<tns:year>2013</tns:year>
<tns:month>11</tns:month>
<tns:date>16</tns:date>
</tns:checkout>
</tns:stayPeriod>
</tns:booking>
1 个解决方案
#1
16
Besides the tutorials mentioned already, here is a simple example that uses javax.xml.transform
and org.w3c.dom
packages:
除了已经提到的教程之外,这里有一个使用javax.xml.transform和org.w3c.dom包的简单示例:
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
public class XML {
public static void main(String[] args) {
XML xml = new XML();
xml.makeFile();
}
public void makeFile() {
Node item = null;
Document xmlDoc = new DocumentImpl();
Element root = xmlDoc.createElement("booking");
item = xmlDoc.createElement("bookingID");
item.appendChild(xmlDoc.createTextNode("115"));
root.appendChild(item);
xmlDoc.appendChild(root);
try {
Source source = new DOMSource(xmlDoc);
File xmlFile = new File("yourFile.xml");
StreamResult result = new StreamResult(new OutputStreamWriter(
new FileOutputStream(xmlFile), "ISO-8859-1"));
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch(Exception e) {
e.printStackTrace();
}
}
}
#1
16
Besides the tutorials mentioned already, here is a simple example that uses javax.xml.transform
and org.w3c.dom
packages:
除了已经提到的教程之外,这里有一个使用javax.xml.transform和org.w3c.dom包的简单示例:
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import com.sun.org.apache.xerces.internal.dom.DocumentImpl;
public class XML {
public static void main(String[] args) {
XML xml = new XML();
xml.makeFile();
}
public void makeFile() {
Node item = null;
Document xmlDoc = new DocumentImpl();
Element root = xmlDoc.createElement("booking");
item = xmlDoc.createElement("bookingID");
item.appendChild(xmlDoc.createTextNode("115"));
root.appendChild(item);
xmlDoc.appendChild(root);
try {
Source source = new DOMSource(xmlDoc);
File xmlFile = new File("yourFile.xml");
StreamResult result = new StreamResult(new OutputStreamWriter(
new FileOutputStream(xmlFile), "ISO-8859-1"));
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch(Exception e) {
e.printStackTrace();
}
}
}