我正在解析XML文档。我之前已经做了好几千次了,但是我不知道为什么我会遇到以下问题:
以下是我正在解析的XML文档的相关部分:
XML: <?xml version="1.0" standalone="yes"?>
<ratings>
<url_template>http://api.netflix.com/users/T1BlCJtdcWMuF6gJEfue96_W.kZ_gW81h59KqLEfT1AzE-/ratings/title?{-join|&|title_refs}</url_template>
<ratings_item>
<user_rating value="not_interested"></user_rating>
<predicted_rating>4.8</predicted_rating>
<id>http://api.netflix.com/users/T1BlCJtdcWMuF6gJEfue96_W.kZ_gW81h59KqLEfT1AzE-/ratings/title/70112530</id>
<link href="http://api.netflix.com/catalog/titles/series/70112530/seasons/70112530" rel="http://schemas.netflix.com/catalog/title" title="Castle: Season 1">
</link>
.
.
.
所以,我试图搞砸user_rating,predict_rating和id。我成功地这样做了。但是,我注意到当user_rating不包含任何值时,predict_rating将自动取值,而不是它自己的值4.8。但是,当user_rating确实有值时,predict_rating将具有正确的值。这是我的解析代码:
public class RatingsHandler extends DefaultHandler {
Vector vector;
Ratings ratings;
boolean inUserRating;
boolean inPredictedRating;
boolean inAverageRating;
boolean inID;
public void startDocument() throws SAXException {
vector = new Vector();
ratings = new Ratings();
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("user_rating")) {
inUserRating = true;
} else if (localName.equals("predicted_rating")) {
inPredictedRating = true;
} else if (localName.equals("average_rating")) {
inAverageRating = true;
} else if (localName.equals("id")) {
inID = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (inUserRating) {
ratings.setUserRating(new String(ch, start, length));
inUserRating = false;
} else if (inPredictedRating) {
ratings.setPredRating(new String(ch, start, length));
inPredictedRating = false;
} else if (inAverageRating) {
ratings.setAvgRating(new String(ch, start, length));
inAverageRating = false;
} else if (inID) {
Const.rating_id = new String(ch, start, length);
inID = false;
}
}
public void endDocument() throws SAXException {
if (ratings != null) {
vector.addElement(ratings);
}
}
public Vector getRatings() {
return vector;
}
}
是否与user_rating具有属性“value”的事实有关?我将不胜感激任何帮助。谢谢!
答案 0 :(得分:3)
我建议你等一下
endElement(String uri, String localName, String qName)
在将元素标记为传递之前:
inSomething = false
我可以想象当元素为空时,
public void characters(char[] ch, int start, int length)
将不会被调用,您的标志将不会被清除,并且您将遇到两个inSomething标志设置为true的不一致状态。