我的要求是处理 xml 文件以搜索字符并替换它。我为此使用以下代码:
public static void main(String[] args) {
try
{
StringBuilder sb = new StringBuilder();
File xmlFile = new File("C:/Users/demo.xml");
BufferedReader br = new BufferedReader(new FileReader(xmlFile));
String line = null;
while((line = br.readLine())!= null){
if(line.indexOf("&") != -1)
{
line = line.replaceAll("&","&");
}
sb.append(line);
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(xmlFile));
Source xmlInput = new StreamSource(new StringReader(sb.toString()));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
bw.write(xmlOutput.getWriter().toString());
bw.close();
System.out.println("success");
}
catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
当我的 xml 文件是:
<INFO>
<NAME>Joseph</NAME>
<BUSINESSNAME>M & A</BUSINESSNAME>
<INFO>
它给出了正确的输出,但格式如下(实际 xml)
<!DOCTYPE CASE SYSTEM "C:\Program Files\abc.dtd">
<INFO>
<NAME>Joseph</NAME>
<BUSINESSNAME>M & A</BUSINESSNAME>
<INFO>
我收到错误:错误:java.io.FileNotFoundException: C:\Program Files\abc.dtd(系统找不到指定的路径)。
有什么解决办法吗?