我有一個文本文件與以下條目轉換文本文件,XML在java中
1
244699000
52.467286666666666
4.611188333333334
我想將其轉換爲XML文件,如下圖所示
<?xml version="1.0" encoding="ISO-8859-1"?>
<SYSTEM-TRACKS>
<AIS-SENSOR ID ="1">
<MMSI>244699000 </MMSI>
<LATITUDE> 52.467286666666666 </LATITUDE>
<LONGITUDE> 4.611188333333334 </LONGITUDE>
</AIS-SENSOR>
</SYSTEM-TRACKS>
這裏是我發現的代碼
public class ToXML {
BufferedReader in;
StreamResult out;
TransformerHandler th;
AttributesImpl atts;
public static void main(String args[]) {
new ToXML().doit();
}
public void doit() {
try {
in = new BufferedReader(new FileReader("data"));
out = new StreamResult("data.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
closeXML();
} catch (Exception e) {
e.printStackTrace();
}
}
public void initXML() throws ParserConfigurationException,
TransformerConfigurationException, SAXException {
// JAXP + SAX
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
th = tf.newTransformerHandler();
Transformer serializer = th.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
// pretty XML output
serializer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(out);
th.startDocument();
atts = new AttributesImpl();
th.startElement("", "", "SYSTEM-TRACKS", atts);
}
public void process(String s) throws SAXException {
String elements[] = s.split("\\r?\\n");
atts.clear();
th.startElement("", "", "AIS-SENSOR", atts);
th.characters(elements[0].toCharArray(), 0, elements[0].length());
th.startElement("", "", "MMSI", atts);
th.characters(elements[1].toCharArray(), 0, elements[1].length());
th.endElement("", "", "MMSI");
th.startElement("", "", "LATITUDE", atts);
th.characters(elements[2].toCharArray(), 0, elements[2].length());
th.endElement("", "", "LATITUDE");
th.startElement("", "", "LONGITUDE", atts);
th.characters(elements[3].toCharArray(), 0, elements[3].length());
th.endElement("", "", "LONGITUDE");
}
public void closeXML() throws SAXException {
th.endElement("", "", "AIS-SENSOR");
th.endElement("", "", "SYSTEM-TRACKS");
th.endDocument();
}
}
但是,當我執行它我得到以下錯誤
java.lang.ArrayIndexOutOfBoundsException: 1
at ToXML.process(ToXML.java:76)
at ToXML.doit(ToXML.java:38)
at ToXML.main(ToXML.java:26)
任何人都可以幫助我做出如上所示的正確的XML文件?
在此先感謝
ArrayIndexOutOfBoundsException異常:拋出以指示數組已被訪問wi非法索引。索引或者是負數,或者大於或等於數組的大小。 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/IndexOutOfBoundsException.html – VirtualTroll 2012-02-27 15:06:20
爲什麼不使用調試器來自己縮小問題的範圍?(如果你不知道怎麼做,我非常建議你學習它,因爲它肯定比在這裏提問更快) – meriton 2012-02-27 15:09:22
看看第76行,它如何訪問外部大小的數組位置? (這是非常基本的,它不會傷害你突出顯示第76行,因爲我當然不會在編輯器中加載你的代碼來自己弄清楚) – KevinDTimm 2012-02-27 15:09:41