使用换行符创建XML文件 [英] Create XML file with linebreaks

查看:182
本文介绍了使用换行符创建XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我参考了以下教程,使用JAVA创建XML文件。
http:// www。 mkyong.com/java/how-to-create-xml-file-in-java-dom/

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/

但是,当我打开xml文件时,它出现在1个极长的单行中。这使得我很难验证结果,并且我确信可以为每个元素标记设置换行符。
但我没有任何线索如何做到这一点。请指教。
以下是我的代码:

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


推荐答案

您需要向变换器对象添加属性。
喜欢这个:

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");

它应该可以解决问题。

这篇关于使用换行符创建XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆