import java.io.File;
import java.sql.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class XmlOutput1 {
public static void main(String[] args) {
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Employee");
doc.appendChild(rootElement);
rootElement.appendChild(getEmployee(doc, "1234", "Anupam", "Engineer", "AManager", "17/10/2014","10000","email"));
rootElement.appendChild(getEmployee(doc, "1235", "Anirban", "Doctor", "BManager", "25/10/2014","20000","phone"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult console = new StreamResult(System.out);
StreamResult console1 = new StreamResult(new File("C:\\Users\\anupam.a.mukherjee\\Desktop\\anupam1.xml"));
transformer.transform(source, console);
transformer.transform(source,console1);
}
catch (Exception e) {
e.printStackTrace();
}
}
private static Node getEmployee(Document document, String empno, String name, String job, String manager,String date,String salary,String communication)
{
Element employee = document.createElement("Employee");
employee.setAttribute("empno", empno);
employee.appendChild(getEmployeeElements(document, employee, "name", name));
employee.appendChild(getEmployeeElements(document, employee, "job", job));
employee.appendChild(getEmployeeElements(document, employee, "manager", manager));
employee.appendChild(getEmployeeElements(document, employee, "date", date));
employee.appendChild(getEmployeeElements(document, employee, "salary", salary));
employee.appendChild(getEmployeeElements(document, employee, "communication", communication));
return employee;
}
private static Node getEmployeeElements(Document document, Element element, String name, String value) {
Element node = document.createElement(name);
node.appendChild(document.createTextNode(value));
return node;
}
private static Node getEmployeeElements1(Document document, Element element, int name, int value) {
Element node = document.createElement(name);
node.appendChild(document.createTextNode(value));
return node;
}
}
现在我的问题是第二个函数是getEmployeeElements1,它给出了错误,因为节点只能接受字符串,所以请告诉我创建整数,日期格式,双..等的节点函数的过程。
答案 0 :(得分:0)
您可以使用生成代码的框架并为容器提供类型化数据,这样您就可以确保在节点中存储正确的值(例如:JAXB),但是当您使用本机DOM时,您将不得不仅操纵文本数据。
在这里,您只需使用static String Integer.toString(int i)
等方法填充DOM对象。