我有这个XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<music>
<artist name="Eminem">
<album title="Recovery" year="2010" art="cover.png">
<song title="Cold Wind Blows" />
<song title="Talkin' 2 Myself"/>
<song title="On Fire"/>
</album>
</artist>
</music>
我用这段代码解析它:
// Get child elements of root
NodeList artistList = document.getElementsByTagName("artist");
for(int i = 0; i < artistList.getLength(); i++)
{
Node artistNode = artistList.item(i);
if(artistNode.getNodeType() == Node.ELEMENT_NODE)
{
// Album list
NodeList albumList = artistNode.getChildNodes();
// Get artist name
String artistName = artistNode.getAttributes().getNamedItem("name").getNodeValue();
for(int j = 0; j < albumList.getLength(); j++)
{
Node albumNode = albumList.item(j).getNextSibling();
String albumTitle = albumNode.getAttributes().getNamedItem("title").getNodeValue();
String albumYear = albumNode.getAttributes().getNamedItem("year").getNodeValue();
String albumArt = albumNode.getAttributes().getNamedItem("art").getNodeValue();
System.out.println(artistName+albumTitle+albumYear+albumArt);
}
}
}
这打印出属性值就好了。但是,当j
为1
时,我会在此行中获得NullPointerException
:
String albumTitle = albumNode.getAttributes().getNamedItem("title").getNodeValue();
我做错了什么?我应该用更少的for循环以不同的方式解析它吗?我想我需要另一个循环来获取歌曲信息。
任何帮助将不胜感激!
完整堆栈跟踪:
EminemRecovery2010cover.png
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.NullPointerException
at songlibrary.SongList.buildSongList(SongList.java:69)
at app.Main.main(Main.java:37)
... 11 more
Exception running application app.Main