使用java创buildXML文件

如何创build一个XML文件,并将其保存在我的机器中的某些地方使用java..there属性还包括在xml文件中? 我find了org.w3c.dom.Document,但是在为元素创build属性时存在问题,并保存了xml文件。

谢谢。

来自这个网站的例子:

try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); //root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); //staff elements Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); //set attribute to staff element Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); //shorten way //staff.setAttribute("id", "1"); //firstname elements Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); //lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); //nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); //salary elements Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); //write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\testing.xml")); transformer.transform(source, result); System.out.println("Done"); }catch(ParserConfigurationException pce){ pce.printStackTrace(); }catch(TransformerException tfe){ tfe.printStackTrace(); } 

您可以使用Xembly这个小型的开源库,使得这个XML创build过程更加直观:

 String xml = new Xembler( new Directives() .add("root") .add("order") .attr("id", "553") .set("$140.00") ).xml(); 

Xembly是本地Java DOM的封装,是一个非常轻量级的库。

看看dom4j或者jdom 。 这两个库允许创build一个文档,并允许打印文档为XML。 两者都使用,很容易使用,你会发现很多的例子和片段。

dom4j – 快速入门指南

刚刚碰巧在这工作,使用https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm从这里的例子,并阅读解释。; 我也提供你自己的例子:

 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.newDocument(); // root element Element rootElement = doc.createElement("words"); doc.appendChild(rootElement); while (ptbt.hasNext()) { CoreLabel label = ptbt.next(); System.out.println(label); m = r1.matcher(label.toString()); //System.out.println(m.find()); if (m.find() == true) { Element w = doc.createElement("word"); w.appendChild(doc.createTextNode(label.toString())); rootElement.appendChild(w); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml")); transformer.transform(source, result); // Output to console for testing StreamResult consoleResult = new StreamResult(System.out); transformer.transform(source, consoleResult); 

这是在使用斯坦福自然语言处理标记器的情况下,只是其中的一部分,以了解如何添加元素。 输出结果是:Billbuyedapples(我从文件中读取了这个句子)

你可能想给XStream一个镜头,这并不复杂。 它基本上做了繁重的工作。

我喜欢Xembly语法,但它不是一个静态types的API。 你可以用XMLBeam得到这个:

 // Declare a projection public interface Projection { @XBWrite("/root/order/@id") Projection setID(int id); @XBWrite("/root/order") Projection setValue(String value); } public static void main(String[] args) { // create a projector XBProjector projector = new XBProjector(); // use it to create a projection instance Projection projection = projector.projectEmptyDocument(Projection.class); // You get a fluent API, with java types in parameters projection.setID(553).setValue("$140.00"); // Use the projector again to do IO stuff or create an XML-string projector.toXMLString(projection); } 

我的经验是,即使在XML变得更复杂的情况下,这种方法也很有效。 你可以把你的java代码结构中的XML结构解耦。

 package com.server; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import org.w3c.dom.*; import com.gwtext.client.data.XmlReader; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; public class XmlServlet extends HttpServlet { NodeList list; Connection con=null; Statement st=null; ResultSet rs = null; String xmlString ; BufferedWriter bw; String displayTo; String displayFrom; String addressto; String addressFrom; Date send; String Subject; String body; String category; Document doc1; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ System.out.print("on server"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); System.out.print("on server"); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = builderFactory.newDocumentBuilder(); //creating a new instance of a DOM to build a DOM tree. doc1 = docBuilder.newDocument(); new XmlServlet().createXmlTree(doc1); System.out.print("on server"); } catch(Exception e) { System.out.println(e.toString()); } } public void createXmlTree(Document doc) throws Exception { //This method creates an element node System.out.println("ruchipaliwal111"); try { System.out.println("ruchi111"); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1"); st = con.createStatement(); rs = st.executeQuery("select * from data"); Element root = doc.createElement("message"); doc.appendChild(root); while(rs.next()) { displayTo=rs.getString(1).toString(); System.out.println(displayTo+"getdataname"); displayFrom=rs.getString(2).toString(); System.out.println(displayFrom +"getdataname"); addressto=rs.getString(3).toString(); System.out.println(addressto +"getdataname"); addressFrom=rs.getString(4).toString(); System.out.println(addressFrom +"getdataname"); send=rs.getDate(5); System.out.println(send +"getdataname"); Subject=rs.getString(6).toString(); System.out.println(Subject +"getdataname"); body=rs.getString(7).toString(); System.out.println(body+"getdataname"); category=rs.getString(8).toString(); System.out.println(category +"getdataname"); //adding a node after the last child node of ssthe specified node. Element element1 = doc.createElement("Header"); root.appendChild(element1); Element child1 = doc.createElement("To"); element1.appendChild(child1); child1.setAttribute("displayNameTo",displayTo); child1.setAttribute("addressTo",addressto); Element child2 = doc.createElement("From"); element1.appendChild(child2); child2.setAttribute("displayNameFrom",displayFrom); child2.setAttribute("addressFrom",addressFrom); Element child3 = doc.createElement("Send"); element1.appendChild(child3); Text text2 = doc.createTextNode(send.toString()); child3.appendChild(text2); Element child4 = doc.createElement("Subject"); element1.appendChild(child4); Text text3 = doc.createTextNode(Subject); child4.appendChild(text3); Element child5 = doc.createElement("category"); element1.appendChild(child5); Text text44 = doc.createTextNode(category); child5.appendChild(text44); Element element2 = doc.createElement("Body"); root.appendChild(element2); Text text1 = doc.createTextNode(body); element2.appendChild(text1); /* Element child1 = doc.createElement("name"); root.appendChild(child1); Text text = doc.createTextNode(getdataname); child1.appendChild(text); Element element = doc.createElement("address"); root.appendChild(element); Text text1 = doc.createTextNode( getdataaddress); element.appendChild(text1); */ } //TransformerFactory instance is used to create Transformer objects. TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); // create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); transformer.transform(source, result); xmlString = sw.toString(); File file = new File("./war/ds/newxml.xml"); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bw.write(xmlString); } catch(Exception e) { System.out.print("after while loop exception"+e.toString()); } bw.flush(); bw.close(); System.out.println("successfully done....."); } }