Я пытаюсь написать программу java, которая будет считываться в CSV-файле с различной информацией о остановке шины и преобразовывать их в XML-файл и сохранять в качестве нового xml-файла. У меня была некоторая помощь с некоторым кодом от друга, но я не мог понять, в чем проблема, поскольку они забыли включить комментарии в код. Любая помощь в исправлении кода будет принята с благодарностью. Код показан ниже.Преобразование CSV-файла в файл XML с использованием Java
public class converter {
protected DocumentBuilderFactory domFactory = null;
protected DocumentBuilder domBuilder = null;
public static void main(String[] args) {
ArrayList<String> busStopInfo = new ArrayList<String>(7);
File file = new File("stops.csv");
BufferedReader readFile = null;
try {
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder db = df.newDocumentBuilder();
Document document = db.newDocument();
Element rootElement = document.createElement("BusStops");
document.appendChild(rootElement);
readFile = new BufferedReader(new FileReader(file));
int line = 0;
String information = null;
while ((information = readFile.readLine()) != null) {
String[] rowValues = information.split(",");
if (line == 0) {
for (String columnInfo : rowValues) {
busStopInfo.add(columnInfo);
}
} else {
Element childElement = document.createElement("details");
rootElement.appendChild(childElement);
for (int columnInfo = 0; columnInfo < busStopInfo.size(); columnInfo++) {
String header = busStopInfo.get(columnInfo);
String value = null;
if (columnInfo < rowValues.length) {
value = rowValues[columnInfo];
} else {
value = " ";
}
Element current = document.createElement(header);
current.appendChild(document.createTextNode(value));
childElement.appendChild(current);
System.out.println(value);
}
}
line++;
}
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer output = new StringWriter();
tf.transform(new DOMSource(document), new StreamResult(output));
System.out.println(output.toString());
} catch (Exception e) {
}
}
}
Ниже приводится выдержка из файла CSV
AtcoCode, CommonName, LocalityName, ParentLocalityName, широта, долгота 0100BRP90336, Центр, Bristol City Center, Bristol, +51,4543379612, - 2,5978824115 0170SGA56570, УВЕ вход North, Abbey Wood ,, +51,50419145, -2,549547265 079073001Z, автовокзал Экспресс Lounge, Мидлсбро ,, +54,5760020508, -1,2391798779 0800COC31523, автовокзал, Ньюквай ,, +50,4130339395, -5,0856695446 0800COC56586, автовокзал, Camborne ,, +50,2132677521, -5,2974299693
Это схема для файла XML я пытаюсь повторить
<xs:element name="Busstops">
<xs:element name="stops" minOccurs="1" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="AtcoCode" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:element name="CommonName" type="xs:string" "minOccurs="1" maxOccurs="1"/>
<xs:element name="LocalityName" type="xs:string" "minOccurs="1" maxOccurs="1"/>
<xs:element name="ParentLocalityName" type="xs:string" "minOccurs="0" maxOccurs="1"/>
<xs:element name="Longitude" type="xs:string" "minOccurs="1" maxOccurs="1"/>
<xs:element name="Latitude" type="xs:string" "minOccurs="1" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
Что не так с кодом? Каким образом вы не выполняете то, что ожидаете? – KevinO
не выводит и не сохраняет файл, у меня нет большого опыта работы с этим языком, поэтому я очень не уверен, если что-то не хватает. Я запускаю код, и никаких свидетельств чего-либо не происходит. – Granto867
Вам нужно будет предоставить пару строк от stops.csv, чтобы отобразить ожидаемый ввод. Было бы лучше, если бы у вас также был короткий пример ожидаемого результата. – KevinO