问题描述
<document>
<root>
<field1>
<a
Type="anyType">
<b>Text</b>
</a>
<field1>
</root>
</document>
我想删除 xml 属性 Type
和 xml 字段 a
中的空格
输出应该是这样的:
<document>
<root>
<field1>
<a Type="anyType">
<b>Text</b>
</a>
<field1>
</root>
</document>
如何在 Java 中执行此操作。
DOMSource domSource = new DOMSource(document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource,result);
String fileData = format(writer.toString());
// remove CR(carriage return)
fileData = fileData.replaceAll("&#[a-zA-Z0-9]{2};","");
saveDocumentIntoFile(fileData,fileName);
方法格式()
public String format(String xml) {
try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();
// Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("format-pretty-print",Boolean.TRUE);
// Set this to true if the declaration is needed to be outputted.
writer.getDomConfig().setParameter("xml-declaration",keepDeclaration);
return writer.writetoString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
方法 saveDocumentIntoFile()
protected void saveDocumentIntoFile(String fileData,String fileName) throws IOException {
FileWriter batchFile = new FileWriter(fileName);
batchFile.write(fileData);
batchFile.close();
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)