首页 > 解决方案 > CSV 到使用 Java/Javascript 的自定义 XML

问题描述

我想用 Java/Javascript 将 CSV 转换为 XML。

例如我的 CSV 文件如下表:


| 身份证 | 奥洛 |

| 12345 | 薄层色谱 |

| 12345 | 虚拟专用网 |

| 67890 | 薄层色谱 |


我想要一个这样的 XML 文件:

<?xml version='1.0' encoding='UTF-8'?>
<Custom name="Custom_ListaOLO">
  <Attributes>
    <Map>
      <entry key="12345">
        <value>
          <List>
            <String>TLC</String>
            <String>VPN</String>
          </List>
        </value>
      </entry>
      <entry key="67890">
        <value>
          <List>
            <String>TLC</String>
          </List>
        </value>
      </entry>
    </Map>
  </Attributes>
</Custom>

或者:

<?xml version='1.0' encoding='UTF-8'?>
<Custom name="Custom_ListaOLO">
  <Attributes>
    <Map>
      <entry key="12345">
        <value>
          <List>
            <String>TLC</String>
            <String>VPN</String>
          </List>
        </value>
      </entry>
      <entry key="67890", value="TLC />
    </Map>
  </Attributes>
</Custom>

你能帮助我吗?

标签: javascriptjavaxmlcsvexport-to-xml

解决方案


you can fulfill the above requirement using JAXB marshaling with the MOXy implementation.

JAXB Java Architecture for XML Binding (JAXB) is a software framework that provides way to map Java classes to XML representations. for more info

JAXB MARSHALING converting the java objects to xml. for more info

MOXy enable developers to handle the complex XML structures. for more info

firstly read the csv file and create java objects, then convert java objects to xml using jaxb marshaling with moxy implementation.

try with following solution,

create two java pojo classes (Custom and Entry) for represented <Custom> and <entry> elements of xml file,

Custom.java

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="Custom")
public class Custom {

    private String name;
    private List<Entry> entry;

    public String getName() {
        return name;
    }

    @XmlAttribute
    public void setName(String name) {
        this.name = name;
    }

    public Custom() {
        entry = new ArrayList<Entry>();
    }

    @XmlPath("Attributes/Map/entry")
    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }
}

Entry.java

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAttribute;
import org.eclipse.persistence.oxm.annotations.XmlPath;

public class Entry {

    private String key;
    private List<String> string;

    public Entry() {
        string = new ArrayList<String>();
    }

    @XmlAttribute
    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @XmlPath("value/List/String/text()")
    public List<String> getString() {
        return string;
    }

    public void setString(List<String> string) {
        this.string = string;
    }
}

read the csv file, create java objects and convert it to xml,

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.xmlmodel.ObjectFactory;

public class Demo {

    public static void main(String[] args) throws JAXBException {
        String line;
        String key = null;
        Custom custom = new Custom();
        Entry entry = null;
        int index = 0;

        try {
            BufferedReader br = new BufferedReader(new FileReader("inputCSV.csv")); //get csv file
            while ((line = br.readLine()) != null) {    //get every single line individually in csv file
                if(index > 0){  //skip the column's names (first line of csv file)
                    String[] value = line.split(",");   //collect the comma separated values (ID and OLO) into array
                    if(key == null || !key.equals(value[0])){   //first line of the csv file and when find the new key value, then create new entry
                        if(entry != null){
                            custom.getEntry().add(entry);   //add entry object into entry list of custom
                        }
                        key = value[0]; //assign the key value to variable (String key) for identify the new entry
                        entry = new Entry();    //create a new entry
                        entry.setKey(value[0]); //assign the key value to entry
                        entry.getString().add(value[1]);    //add string value String list of entry with new key
                    }else{
                        entry.getString().add(value[1]);    //add string value String list of entry under the same key
                    }
                }
                index++;
            }
            custom.setName("Custom_ListaOLO");  //set value to name attribute of custom element
            custom.getEntry().add(entry);   //add last entry into entry list of custom
        } catch (IOException e) {
            e.printStackTrace();
        }

        //marshaling with JAXB
        JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[]{Custom.class, ObjectFactory.class}, null);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(custom, new File("output.xml")); //generate the output xml file
        marshaller.marshal(custom, System.out);
    }
}

inputCSV.csv

ID,OLO
12345,TLC
12345,VPN
67890,TLC

output.xml

<?xml version="1.0" encoding="UTF-8"?>
<Custom name="Custom_ListaOLO">
   <Attributes>
      <Map>
         <entry key="12345">
            <value>
               <List>
                  <String>TLC</String>
                  <String>VPN</String>
               </List>
            </value>
         </entry>
         <entry key="67890">
            <value>
               <List>
                  <String>TLC</String>
               </List>
            </value>
         </entry>
      </Map>
   </Attributes>
</Custom>

推荐阅读