如何在 Java 中将转义字符读取为文本?


public List<String> readRSS(String feedUrl, String openTag, String closeTag)
throws IOException, MalformedURLException {
URL url = new URL(feedUrl);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String currentLine;
List<String> tempList = new ArrayList<String>();
while ((currentLine = reader.readLine()) != null) {
Integer tagEndIndex = 0;
Integer tagStartIndex = 0;
while (tagStartIndex >= 0) {
tagStartIndex = currentLine.indexOf(openTag, tagEndIndex);
if (tagStartIndex >= 0) {
tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
tempList.add(currentLine.substring(tagStartIndex + openTag.length(), tagEndIndex) + "n");
}
}
}
if (tempList.size() > 0) {
if(openTag.contains("title")){
tempList.remove(0);
tempList.remove(0);
}
else if(openTag.contains("desc")){
tempList.remove(0);
}
}
return tempList;
}

我写这段代码是为了阅读RSS提要。一切都很好,但是当解析器找到这样的字符时&#xD;它就会中断。这是因为它找不到其结束标记,因为 xml 已转义。

我不知道如何在代码中修复它。谁能帮我解决这个问题?

问题是特殊字符&#xD;是换行符,因此您的开始和结束标签在不同的行上结束。因此,如果您逐行阅读,则它将无法与您拥有的代码一起使用。

你可以尝试这样的事情:

StringBuffer fullLine = new StringBuffer();
while ((currentLine = reader.readLine()) != null) {
int tagStartIndex = currentLine.indexOf(openTag, 0);
int tagEndIndex = currentLine.indexOf(closeTag, tagStartIndex);
// both tags on the same line
if (tagStartIndex != -1 && tagEndIndex != -1) {
// process the whole line
tempList.add(currentLine);
fullLine = new StringBuffer();
// no tags on this line but the buffer has been started
} else if (tagStartIndex == -1 && tagEndIndex == -1 && fullLine.length() > 0) {
/*
* add the current line to the buffer; it is part 
* of a larger line
*/
fullLine.append(currentLine);
// start tag is on this line
} else if (tagStartIndex != -1 && tagEndIndex == -1) {
/*
*  line started but did not have an end tag; add it to 
*  a new buffer
*/
fullLine = new StringBuffer(currentLine);
// end tag is on this line
} else if (tagEndIndex != -1 && tagStartIndex == -1) {
/*
*  line ended but did not have a start tag; add it to 
*  the current buffer and then process the buffer
*/
fullLine.append(currentLine);
tempList.add(fullLine.toString());
fullLine = new StringBuffer();
}
}

给定此示例输入:

<title>another &#xD;
title 0</title>
<title>another title 1</title>
<title>another title 2</title>
<title>another title 3</title>
<desc>description 0</desc>
<desc>another &#xD;
description 1</desc>
<title>another title 4</title>
<title>another &#xD;
another line in between &#xD;
title 5</title>

titletempList中的完整行变为:

<title>another &#xD;title 0</title>
<title>another title 1</title>
<title>another title 2</title>
<title>another title 3</title>
<title>another title 4</title>
<title>another &#xD;another line in between &#xD;title 5</title>

对于desc

<desc>description 0</desc>
<desc>another &#xD;description 1</desc>

您应该测试此方法在完整 RSS 源上的性能。另请注意,特殊字符不会被转义。

最新更新