我有以下代码将文本文件转换为xml。: -
**
public static void main (String args[]) {
new ToXML().doit();
}
public void doit () {
try{
in = new BufferedReader(new FileReader("D:/sample.txt"));
out = new StreamResult("D:/data.xml");
initXML();
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
in.close();
writeXML();
}
catch (Exception e) { e.printStackTrace(); }
}
public void initXML() throws ParserConfigurationException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
xmldoc = impl.createDocument(null, "AIRLINE_INFO", null);
root = xmldoc.getDocumentElement();
}
public void process(String s) {
String elements = s;
Element e1 = xmldoc.createElement("Supplier_Name");
Node n1 = xmldoc.createTextNode(elements);
e1.appendChild(n1);
Element e2 = xmldoc.createElement("E-Mail_Address");
Node n2 = xmldoc.createTextNode(elements);
e2.appendChild(n2);
e0.appendChild(e1);
e0.appendChild(e2);
root.appendChild(e0);
}
public void writeXML() throws TransformerConfigurationException,
TransformerException {
DOMSource domSource = new DOMSource(xmldoc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(domSource, out);
}
}
**
预期的输出是: **
<AIRLINE_INFO>
<AIRTICKET>
<Supplier_Name>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</Supplier_Name>
<E-Mail_Address>E-Mail: custrelations@spicejet.com</E-Mail_Address>
</AIRTICKET>
</AIRLINE_INFO>
**
但目前在执行代码时我得到以下输出
**
<AIRLINE_INFO>
<AIRTICKET>
<Supplier_Name>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</Supplier_Name>
<E-Mail_Address>SpiceJet Ltd, 319, Udyog Vihar, Phase IV, Gurgaon - 122016 Haryana, India</E-Mail_Address>
</AIRTICKET>
<AIRTICKET>
<Supplier_Name>E-Mail: custrelations@spicejet.com</Supplier_Name>
<E-Mail_Address>E-Mail: custrelations@spicejet.com</E-Mail_Address>
</AIRTICKET>
</AIRLINE_INFO>
**
请帮助我如何打破对象以实现预期输出。
答案 0 :(得分:1)
这里为文本节点使用两次相同的字符串:
String elements = s;
Element e1 = xmldoc.createElement("Supplier_Name");
Node n1 = xmldoc.createTextNode(elements);
e1.appendChild(n1);
Element e2 = xmldoc.createElement("E-Mail_Address");
Node n2 = xmldoc.createTextNode(elements);
e2.appendChild(n2);
要解决此问题,您需要阅读两行,然后使用该信息创建一个机票节点。