CSV в Custom XML с Java / Javascript - PullRequest
1 голос
/ 07 мая 2020

Я хочу преобразовать из CSV в XML с помощью Java / Javascript.

Например, мой CSV-файл выглядит как эта таблица:


| ID | OLO |

| 12345 | TL C |

| 12345 | VPN |

| 67890 | TL C |


Я хотел бы иметь файл 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>

Можете ли вы помочь меня?

1 Ответ

1 голос
/ 08 мая 2020

вы можете выполнить указанное выше требование, используя маршалинг JAXB с реализацией MOXy.

JAXB Java Архитектура для XML Binding (JAXB) - это программная среда, которая обеспечивает способ сопоставить классы Java с XML представлениями. для получения дополнительной информации

JAXB MARSHALING преобразование объектов java в xml. для получения дополнительной информации

MOXy позволяет разработчикам обрабатывать сложные структуры XML. для получения дополнительной информации

сначала прочтите файл csv и создайте java объекты, затем преобразуйте java объекты в xml, используя маршалинг jaxb с реализацией moxy.

попробуйте со следующим решением:

создать два java класса pojo (Custom и Entry) для представленных <Custom> и <entry> элементов xml файла,

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;
    }
}

прочитать файл csv, создать java объектов и преобразовать его в 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...