gpt4 book ai didi

java - 如何逐行打印字符串对象

转载 作者:行者123 更新时间:2023-12-01 12:40:21 24 4
gpt4 key购买 nike

我有以下代码将文本文件转换为 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>

**

请帮助我如何破坏该对象以实现预期输出。

最佳答案

您在此处对文本节点使用相同的字符串两次:

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);

要解决此问题,您需要读取两行,然后使用该信息创建一个机票节点。

关于java - 如何逐行打印字符串对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25163089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com