2015-12-28 157 views
0

我想用下面的格式生成XML文件。Xml文件生成

'<root> 
<row serialno="1234"/> 
<row serialno="12345"/> 
</root>' 

我能夠以下面的格式生成XML文件。在Java中生成一個XML文件書面

<?xml version = '1.0' encoding = 'UTF-8'?> 
<root> 
<serialno>1</serialno> 
<serialno>2</serialno> 
<serialno>3</serialno> 
<serialno>4</serialno> 
</root> 

代碼:

public static void main(String[] args) { 
     CreateXmlFileDemo createXmlFileDemo = new CreateXmlFileDemo(); 
     XmlType reqInXml; 
     XmlType reqOutXML; 

     StringBuilder sb = new StringBuilder(); 
     try { 
//   Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
      DocumentBuilderFactory dbFactory =DocumentBuilderFactory.newInstance(); 
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
      Document doc = dBuilder.newDocument(); 
      // root element 
      Element rootElement = doc.createElement("root"); 
      doc.appendChild(rootElement); 

      // staff elements 
//   Element row = doc.createElement("row"); 
//   rootElement.appendChild(row); 


      // firstname elements 
      for(int i=1; i<5;i++){ 
       String strI = "serialno"; 
       String testValue = Integer.toString(i); 
       Element serialno = doc.createElement(strI);  
       serialno.appendChild(doc.createTextNode(testValue)); 
       sb.append(serialno); 
       System.out.println(sb.toString()); 
       rootElement.appendChild(serialno); 
      } 


      // write the content into xml file 
      TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
      Transformer serializer = TransformerFactory.newInstance().newTransformer(); 
      Transformer transformer = transformerFactory.newTransformer(); 
      DOMSource source = new DOMSource(doc); 
      StringWriter stw = new StringWriter(); 
      serializer.transform(new DOMSource(doc), new StreamResult(stw)); 
      StreamResult result = new StreamResult(new File("D:\\Files.xml")); 
      System.out.println(stw.toString()); 
      // Output to console for testing 
      // StreamResult result = new StreamResult(System.out); 

      transformer.transform(source, result); 
      System.out.println("File saved!"); 

     }catch (ParserConfigurationException pce) { 
     pce.printStackTrace(); 
    } catch (TransformerException tfe) { 
     tfe.printStackTrace(); 
    } 
     catch (Exception e) { 
         e.printStackTrace(); 
       } 
    } 
} 

可以在任何1幫我生成XML文件,如下面的格式不在話下。

回答

0

您需要更改這段代碼

// firstname elements 
     for(int i=1; i<5;i++){ 
      Element row= doc.createElement("row");  
      row.setAttribute("serialno",Integer.toString(i)); 
      rootElement.appendChild(row); 
     }