[英]How do i correctly parse my csv file using DOM?
我設法獲得了輸出XML的文件。 但是由於某種原因,當parentLocalityName中不存在某個元素時,只會顯示結束標記,如下所示,您可以看到僅顯示結束標記。 我如何更改代碼以使整個標簽出現但里面沒有內容?
-<BusStopDetails>
<AtcoCode>0800COC31523</AtcoCode>
<CommonName>Bus Station</CommonName>
<LocalityName>Newquay</LocalityName>
<ParentLocalityName/>
<Latitude>50.4130339395</Latitude>
<Longitude>-5.0856695446</Longitude>
</BusStopDetails>
這是我的Java程序,用於轉換文件:
import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
public class CSV2XML {
// Protected Properties
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;
// CTOR
public CSV2XML() {
try {
domFactory = DocumentBuilderFactory.newInstance();
domBuilder = domFactory.newDocumentBuilder();
} catch (FactoryConfigurationError exp) {
System.err.println(exp.toString());
} catch (ParserConfigurationException exp) {
System.err.println(exp.toString());
} catch (Exception exp) {
System.err.println(exp.toString());
}
}
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException, TransformerException {
ArrayList<String> busStopInfo = new ArrayList<String>(7);
// An array list has been used to store the elements from the csv file. They are stored as strings.
try {
File file = new File("C:\\Users\\liaml\\OneDrive\\Documents\\CSCU9T4 XML assignment\\lrl00002\\stops.csv");
BufferedReader readFile = null;
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
db = df.newDocumentBuilder();
Document doc = db.newDocument();
// Root element
Element rootElement = doc.createElement("BusStops"); // root element "Busstops created"
doc.appendChild(rootElement);
readFile = new BufferedReader(new FileReader(file));
int line = 0; // Represent the lines in the file, starts at the 0th,
// increments after every line has been tokenised
// for elements line of the file
String information = null;
while ((information = readFile.readLine()) != null) {
String[] tokens = information.split(","); // removes comma until there is no more commas
String[] row = information.split(","); // store elements after the command, length 6 to store headers
if (line == 0) {
for (String column : row) {
busStopInfo.add(column); // This will add column headers from rowValues to busStopInfo ArrayList
}
} else {
Element childElement = doc.createElement("BusStopDetails"); // creates child element details
rootElement.appendChild(childElement);
for (int column = 0; column < busStopInfo.size(); column++) {
String header = busStopInfo.get(column);
String value = null;
if (column < row.length) {
value = row[column];
} else {
value = " ";
}
Element current = doc.createElement(header); // creates element of current header
current.appendChild(doc.createTextNode(value)); // creates placement for value
childElement.appendChild(current); // adds current value of the header into child element details
// Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
Source src = new DOMSource(doc);
information = ("C:\\Users\\liaml\\OneDrive\\Documents\\CSCU9T4 XML assignment\\lrl00002\\stops.xml");
Result dest = new StreamResult(new File(information));
aTransformer.transform(src, dest);
if (line >= 0) {
System.out.println("CSV File has been successfully converted to XML File & Stored in Zip Folder "
+ "(" + String.valueOf(line) + " row)");
} else {
System.out.println(
"Error while converting input CSV File " + args[0] + " to output XML File " + args[1] + " ");
}
}
}
line++;
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}
<ParentLocalityName/>
是一個空標記。
</ParentLocalityName>
是結束標記。
不一樣的東西。
空標簽( 請參閱XML規范 )是開始標簽和結束標簽的簡寫。
<ParentLocalityName></ParentLocalityName>
<ParentLocalityName/>
上面兩行表示的是完全相同的事物,並且一旦解析就無法區分。
順便說一句:您的標題是虛假的:您無法使用 DOM 解析 CSV文件。
您正在讀取CSV文件並使用DOM 編寫 XML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.