查看我的 xml 的这一部分:
<blocktype>
<properties name="normal_blue" type="1"/>
<resources image="brick_blue"/>
<properties powerup="0" shield="0" />
</blocktype>
我正在使用此代码来解析它:
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase("level")) {
block = null;
inLevel = true; // parsing level
Log.d("MyContentHandler", "Parsing Level = " + Boolean.toString(inLevel));
} if (localName.equalsIgnoreCase("blocktype")) {
bundle = null;
inBlockType = true; // parsing blocktype
Log.d("MyContentHandler", "Parsing blocktype = " + Boolean.toString(inBlockType));
};
// handling level parsing
if (inLevel) {
int n = 0;
if (localName.equalsIgnoreCase("properties")) {
int c = Integer.parseInt(attributes.getValue("columns"));
int r = Integer.parseInt(attributes.getValue("rows"));
bundle = new XmlLevelBundle(r, c);
bundle.name = attributes.getValue("name");
}// bundle might be null?
if (localName.equalsIgnoreCase("block")) {
bundle.types[n] = Integer.parseInt(attributes.getValue("type"));
n++;
}
}
// handling BlockType parsing
if (inBlockType) {
if (localName.equalsIgnoreCase("properties")) {
block.name = attributes.getValue("name");
block.type = Integer.parseInt(attributes.getValue("type")); //nullpointer?
} else if (localName.equalsIgnoreCase("resources")) {
block.resourceName = attributes.getValue("image");
} else if (localName.equalsIgnoreCase("properties")) {
block.powerUp = Integer.parseInt(attributes.getValue("powerup"));
block.shield = Integer.parseInt(attributes.getValue("shield"));
}
}
}
现在,当我删除第二条语句时,一切似乎都有效。正如您所看到的,我的 xml 实际上具有 type
属性,但根据以下 logcat,它仍然返回 null:
12-09 18:53:30.741: WARN/System.err(851): java.lang.NumberFormatException: unable to parse 'null' as integer 12-09 18:53:30.769: WARN/System.err(851): at java.lang.Integer.parseInt(Integer.java:406) 12-09 18:53:30.769: WARN/System.err(851): at java.lang.Integer.parseInt(Integer.java:382) 12-09 18:53:30.779: WARN/System.err(851): at cd.ark.utils.MyContentHandler.startElement(MyContentHandler.java:57)
...(sorry for formatting)
所以基本上它说 Null 正在被传递到 Integer.parseInt() 中。
那么有人可以帮我解决这个 NullPointerException 吗? 我已经被困在这个问题上很长时间了。 谢谢!
最佳答案
由于标签之一是“saxparser”,我假设这就是您正在使用的标签。在这种情况下,方法调用看起来是正确的,问题在于 attributes
未使用 XML 包含的值正确初始化。请添加代码以显示如何生成属性
。
编辑:问题可能是这样的
attributes.getValue("rows")
返回 null,因为您没有使用 qualified names在您的 XML 中;请参阅documentation on the SAX library ,特别是 Attributes.getValue(String) 的文档。如果您使用 Attributes.getValue(String)
并且限定名称不可用,它将返回 null
。
可以在 here 找到有关 SO 限定名称的有用但简短的解释。 .
EDIT2:我不知道如何正确调整 XML(我自己从未使用过 XML),但您不必使用命名空间,您也许可以通过以下方式执行您想要的操作使用 Attributes.getValue(int) ,因为它不适用于属性名称,但适用于它所保存的属性列表。不过,您可能需要弄清楚属性的顺序;你可以这样算出来:
for(int i = 0; i < attributes.getLength(); i++) {
System.out.println(attributes.getValue(i));
}
希望有帮助;也许你可以在 SO 上的 XML 中找到一些有用的命名空间;否则,如果您的程序需要使用属性名称来寻址,您可能必须了解 XML 命名空间。
关于java - 解析 xml : attributes. getValue() 返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8450501/