【问题标题】:How to convert a text file to xml with sub elements in java如何在java中使用子元素将文本文件转换为xml
【发布时间】:2016-06-29 06:01:20
【问题描述】:

我在另一个线程上看到了此代码,但无法将其转换为正确格式的文本文件,以使用子元素转换为 xml。而不是输出一个简单的xml

从这里:

Example One
Example Two
Example Three

到这里:

 <?xml version="1.0" encoding="UTF-8"?>
  <inserts>
    <option>Example One</option>
    <option>Example Two</option>
    <option>Example Three</option>
  </inserts>

我需要从文本文件进行以下转换:

 first_main_elem
 f_child_elem1:one
 f_child_elem2:two
 second_main_elem
 s_child_elem1:one
 s_child_elem1:two
 third_standalone_element: null value
 fourth_element:stand alone

到:

 <?xml version="1.0" encoding="UTF-8"?>
  <first_main_elem>
      <f_child_elem1>one</f_child_elem1>
       <f_child_elem1>two</f_child_elem1>
        <f_child_elem1>three</f_child_elem1>
  </first_main_element>
  <second_main_elem>
         <s_child_elem1>one</s_child_elem>
         <s_child_elem2>two</s_child_elem2>
   </second_main_elem>
   <fourth_standalone_elem/> 
   <fifth_element>stand alone</fifth_element>

贴出的代码:

import java.io.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
import javax.xml.transform.*; 
import javax.xml.transform.stream.*;
import javax.xml.transform.sax.*;

 public class ToXML {

 BufferedReader in;
 StreamResult out;
 TransformerHandler th;

 public static void main(String args[]) {
    new ToXML().begin();
}

 public void begin() {
    try {
        in = new BufferedReader(new FileReader("data.txt"));
        out = new StreamResult("data.xml");
        openXml();
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
         in.close();
         closeXml();
      } catch (Exception e) {
        e.printStackTrace();
     }
  }

      public void openXml() throws ParserConfigurationException,TransformerConfigurationException, SAXException{ 

    SAXTransformerFactory tf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
    th = tf.newTransformerHandler();

    // pretty XML output
    Transformer serializer = th.getTransformer();
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");

    th.setResult(out);
    th.startDocument();
    th.startElement(null, null, "inserts", null);
}

   public void process(String s) throws SAXException {
    th.startElement(null, null, "option", null);
    th.characters(s.toCharArray(), 0, s.length());
    th.endElement(null, null, "option");
  }

  public void closeXml() throws SAXException {
    th.endElement(null, null, "inserts");
    th.endDocument();
   }
}

感谢您对此提出任何建议或意见。

【问题讨论】:

    标签: java xml


    【解决方案1】:

    草稿版本请在下面找到,但对解析空节点有更多改进:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    
    import org.xml.sax.SAXException;
    
    public class ToXML {
    
        BufferedReader in;
        StreamResult out;
        TransformerHandler th;
    
        public static void main(String args[]) {
            new ToXML().begin();
        }
    
        public void begin() {
            try {
                in = new BufferedReader(new FileReader(
                        "data.txt"));
                out = new StreamResult("data.xml");
    
                openXml();
                String str;
    
                String[] elements = null;
    
                // skip first line in input file
                in.readLine();
    
                while ((str = in.readLine()) != null) {
    
                    if (str.contains(":")) {
                        elements = str.split(":");
                        process(elements[0], elements[1]);
    
                    } else {
                        th.startElement(null, null, str, null);
                    }
                }
                in.close();
                closeXml("first_main_elem");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void openXml() throws ParserConfigurationException,
                TransformerConfigurationException, SAXException {
    
            SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
                    .newInstance();
            th = tf.newTransformerHandler();
    
            // pretty XML output
            Transformer serializer = th.getTransformer();
            serializer.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "4");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    
            th.setResult(out);
            th.startDocument();
            th.startElement(null, null, "first_main_elem", null);
        }
    
        public void process(String tag, String s) throws SAXException {
            th.startElement(null, null, tag, null);
            th.characters(s.toCharArray(), 0, s.length());
            th.endElement(null, null, tag);
        }
    
        public void closeXml(String s) throws SAXException {
            th.endElement(null, null, s);
            th.endDocument();
        }
    }
    

    【讨论】:

    • 谢谢 Bhargav - 我会试试这个
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 2014-06-27
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多