我试图编写一个代码,它将使用sax读取并保存到一个xml文件中,但我对此很陌生,所以我不断收到标题中的错误。这里是代码:SaxParserException文件过早结束
public void readMoviesFromXML()
{
ArrayList<Movie> lst = new ArrayList<>();
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("movies.xml");
//I get the error at the line just above
Node root = document.getDocumentElement();
NodeList nodeList = root.getChildNodes();
for(int i=0; i<nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if(node instanceof Element)
{
Element element = (Element) node;
Attr attr = element.getAttributeNode("moviename");
String moviename = attr.getValue();
String title = getNodeValue(element, "name");
String rented = getNodeValue(element, "renttimes");
Movie movie = new Movie(title, Integer.parseInt(rented));
lst.add(movie);
}
}
}catch (Exception e)
{
e.printStackTrace();
}
mm.setMovieMap(lst);
}
xml文件未初始化,我担心这可能是问题。 任何帮助表示赞赏。
您是否尝试使用XDocument解析? – Apoorv
我对XML不熟悉,所以我不知道XDocument是什么。 –
wait..let我给你一个关于如何解析XML文档的链接! – Apoorv