我正在尝试使用Java解析XML文件。
在开始解析之前,我需要替换(编码)<code></code>标记之间的一些文本。

因此,我将文件的内容读入一个字符串:

File xml = new File(this.xmlFileName);
final BufferedReader reader = new BufferedReader(new FileReader(xml));
final StringBuilder contents = new StringBuilder();
while (reader.ready()) {
    contents.append(reader.readLine());
}
reader.close();
final String stringContents = contents.toString();


将XML读入字符串后,使用PatternMatcher对值进行编码:

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("<code>(.*?)</code>", Pattern.DOTALL);
Matcher m = p.matcher(stringContents);
while (m.find()) {
    //Encode text between <code> and </code> tags
    String valueFromTags = m.group(1);
    byte[] decodedBytes = valueFromTags.getBytes();
    new Base64();
    String encodedBytes = Base64.encodeBase64String(decodedBytes);
    m.appendReplacement(sb, "<code>" + encodedBytes + "</code>");
}
m.appendTail(sb);
String result = sb.toString();


替换完成后,我尝试将此String读入XML解析器:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(result);
doc.getDocumentElement().normalize();


但随后出现此错误:java.net.MalformedURLException: no protocol: <root> <application> <interface>...

如您所见,在我将File读入String后,由于某些原因,添加了很多空格,原始文件中有换行符或选项卡。所以我认为这就是我收到此错误的原因。有什么办法可以解决这个问题?

最佳答案

我认为您仍然需要检查readLine是否未返回null。

while ((line = reader.readLine()) != null) {
   contents.append(line)
}

09-10 08:12
查看更多