【发布时间】:2014-05-15 23:16:39
【问题描述】:
我正在尝试使用 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 读入字符串后,我使用 Pattern 和 Matcher 对值进行编码:
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 后,由于某些原因,添加了很多空格,原始文件中有换行符或制表符。所以我认为这就是我收到此错误的原因。有什么办法可以解决吗?
【问题讨论】:
-
Obligatory link。我认为这是为什么你应该永远这样做的一个典型例子。
-
那么在
和标签之间编码文本的正确方法是什么?因为我无法在编码之前对其进行解析,所以它包含像 这样的特殊字符,因此解析器会出错。但请注意,在我的示例中解析器无法解析 xml 的问题与我使用 BufferedReader 将其读入字符串的方式有关。在正则表达式更改之前,空格已经存在。 -
那么,您没有有效的 XML。找到一些有效的 XML。
-
如果我让解析器读取由 BufferedReader 读取的 File 对象而不是 String,解析器可以工作并且没有任何错误。所以 XML 是有效的。但是为了进行替换,我必须先将它读入一个字符串,这就是它出错的地方。
标签: java xml dom bufferedreader