有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

正则表达式替换后的java格式错误的xml

我正在尝试用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之后,由于某些原因,添加了大量空格,其中原始文件中有换行符或制表符。所以我想这就是我犯这个错误的原因。我有办法解决这个问题吗


共 (1) 个答案

  1. # 1 楼答案

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

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