java - 如何将 XML 文档导出到文件系统
问题描述
我试图将文本文件转换为 xml 文件,但是在解析时遇到了一个小问题。
这是将txt文件转换为xml的代码。
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("E:/Java Codes/JMartin.txt"));
out = new StreamResult("E:/Java Codes/JMartin2.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
closeXML();
} catch (IOException | ParserConfigurationException | TransformerConfigurationException | SAXException e) {
}
}
public void initXML() throws ParserConfigurationException,
TransformerConfigurationException, SAXException {
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
.newInstance();
th = tf.newTransformerHandler();
Transformer serializer = th.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
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("", "", "Author", atts);
}
public void process(String s) throws SAXException {
String[] elements = s.split("<>;");
atts.clear();
th.startElement("", "", "Data", atts);
th.startElement("", "", "AuthorName", atts);
th.characters(elements[0].toCharArray(), 0, elements[0].length());
th.endElement("", "", "AuthorName");
th.endElement("", "", "Data");
}
public void closeXML() throws SAXException {
th.endElement("", "", "Author");
th.endDocument();
}
}
在编译过程中,代码运行良好,但如何将 .xml 文件保存在驱动器中?
有任何想法吗?请帮忙。
解决方案
您可以使用 aFileWriter
将 XML 文档导出为 XML 文件。
public void saveTo(Document document, File file) {
try (Writer writer = new FileWriter(file)) {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
/*
* Customize your transformer here:
* - Indentation
* - Encoding
* - ...
*/
transformer.transform(new DOMSource(document), new StreamResult(writer));
}
}
推荐阅读
- javascript - Javascript仅在加法/减法的情况下执行/计算括号的使用,而不是在乘法中?
- python - 如何在 SQLAlchemy 中的 python 中回滚 dataframe.to_sql?
- python - 想要在使用 on_touch_down 方法单击它时访问小部件(此处为 OneLineListItem)的文本和 id
- javascript - JS 等待获取 => [对象响应]
- sql-server - 在 SQL Server 中调用 SMS 发送 API 时的身份验证错误
- r - 通过 R-Shiny 连接到数据库的 WSL
- python - 谷歌云上的谷歌应用部署导致[错误13]
- php - Codeigniter 4 在本地运行良好,但在线生产服务器出现错误:CodeIgniter\View\Exceptions\ViewException
- angular - 使用 RxJS 如何通过另一个动作流触发 observables
- javascript - 从特定索引的数组数组中删除重复的 id