文件输出
解析内容
// 字符串内容
String str1= "<info>\n <num>2222222</num>\n<data>2021年03月09日</data>\n<name>李四</name>\n<age>999</age>\n</info>";
String str2= "<info><num>11111111</num><data>2021年03月09日</data><name>张三</name><age>999</age></info>";
文件输出
// 文件输出
FileWriter fileWriter = new FileWriter(new File("文件地址"));
fileWriter.write(format(str1));
fileWriter.flush();
fileWriter.close();
XML格式化输出带标签的字符串
// 字符串格式化为xml文本类型
public String format(String xmlStr) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlStr));
final Document document = db.parse(is);
OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);
return out.toString();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
效果展示