[英]How Can I convert a tilde separated csv file into xml in java
1RW~800~4~22~1~48:2~true
1RW~800~16~39~1~48:2~true
1RW~800~640~330~1~48:2~true
1RW~800~40~124~1~48:2~true
this is my csv file text and i want to read this and put each value in a row separated by ~ into different xml element .这是我的 csv 文件文本,我想阅读它并将每个值放在由 ~ 分隔的行中,放入不同的 xml 元素中。 I will loop through this and form 4 different xmls
我将遍历这个并形成 4 个不同的 xml
You can use OpenCSV (short tutorial here ) to read your CSV file andwrite it to a XML .您可以使用OpenCSV ( 此处的简短教程)读取您的 CSV 文件并将其写入 XML 。
Here is one way this could be done using the mentioned technologies这是使用上述技术可以完成的一种方法
// create the CSVReader
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '~');
// create the DocumentBuilder which will create our xml documents
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// create the transoformer which will make the xml ready for storing
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// loop through the 4 rows
for (int i = 0; i < 4; i++) {
// read one row from the csv
String [] line = reader.readNext()
// create an xml document
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("data-"+i);
doc.appendChild(rootElement);
// iterate over the entries in the row
for (String s : line) {
Element element = doc.createElement("element");
element.appendChild(doc.createTextNode(s));
rootElement.appendChild(element);
}
// finally save it:
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("file_"+i+".xml"));
transformer.transform(source, result);
System.out.println("File " + i + " saved!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.