Create XML file with linebreaks [duplicate]

故事扮演 提交于 2019-12-08 07:44:54

问题


I referred to the following tutorial to create XML file using JAVA. http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/

However, when I open the xml file, it appears in 1 extremely long single line. This makes it very hard for me to verify the result, and I am sure it is possible to have linebreaks for every element tag. But I do not have any clue how to do that. Please advise. Following is my code:

 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ir;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import java.io.File;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

//##############################################################################################################
public class IR {

    public static void main(String[] args) {

        IR obj = new IR();
    obj.Reader();


    }//end main

//##############################################################################################################  
    public void Reader() {

    String csvFile = "TWEETS.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
        String[] heading = {};          //The headings (E.g. ID, Message, Link)
        String[] content = {};         
        int counter = 0;                //Num of columns
        boolean isheading = true;       //First line is heading

    try 
        {
            //##############################################################################################################
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

            // <add> elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("add");
            doc.appendChild(rootElement);
            //##############################################################################################################

            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) 
            {

                    //The first line is heading
                    if(isheading)
                    {
                        //The headings (E.g. ID, Message, Link)
                        heading = line.split(cvsSplitBy);
                        counter = heading.length;       //get number of columns
                        isheading = false;              
                        continue;                       //Go to next loop
                    }else{  //2nd line onwards
                        content = line.split(cvsSplitBy);
                        System.out.println("SG News "
                            + "[ID= " + content[0] 
                            + " , FULL_MESSAGE=" + content[1] + "]");
                    }

                    //##############################################################################################################
                    // <doc> elements
                    Element docEle = doc.createElement("doc");
                    rootElement.appendChild(docEle);                        

                        //Loop according to number of columns
                        for(int i=0; i<counter; i++)
                        {
                            // <field> elements
                            Element fieldEle = doc.createElement("field");
                            rootElement.appendChild(fieldEle);

                            // set attribute to <field> element
                            Attr attr = doc.createAttribute("name");
                            attr.setValue(heading[i]);
                            fieldEle.setAttributeNode(attr);
                            fieldEle.appendChild(doc.createTextNode(content[i]));
                        }
                    //##############################################################################################################

            }
            //##############################################################################################################
            // 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("TWEETs_solr.xml"));

            // Output to console for testing
            transformer.transform(source, result);

            System.out.println("File saved!");
            //##############################################################################################################
    }catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    }catch (TransformerException tfe) {
        tfe.printStackTrace();
    }catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
    }finally {
            if (br != null) 
            {
                try {
                        br.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
            }
    }
    System.out.println("Done"); 

  }//end Reader
 //##############################################################################################################


}//end class

回答1:


You need to add properties to your transformer object. Like this:

Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

it should do the trick.



来源:https://stackoverflow.com/questions/22790146/create-xml-file-with-linebreaks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!