Got a zero-sized list when using XPath to parse xml

53 views Asked by At

My code is like:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet;
import org.dom4j;
import org.jaxen.JaxenException;

/**
 * Servlet implementation class Search
 */
//@WebServlet("/Search")
public class Search extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String xmlName = "rows.xml";
    private static Document document;
    /**
     * @throws DocumentException 
     * @see HttpServlet#HttpServlet()
     */
    public Search() throws DocumentException {
        super();
        XmlReader xmlReader = new XmlReader();
        document = xmlReader.readXml();
        searcher();
    }

The code that occured the unexpected output:

 public void searcher()
    {
        List nodelist = document.selectNodes("rows");
        System.out.println(nodelist.size());
    }
}

My XML reader:

package web.app;
import org.xml.sax.helpers.DefaultHandler;
import org.dom4j;

public class XmlReader extends DefaultHandler{
    public static String filename = 
    "D:\\JavaWorkplace\\DataCuration\\WebContent\\rows.xml";
public Document readXml() throws DocumentException {
    SAXReader saxReader = new SAXReader();
    Document document = saxReader.read(filename);
    System.out.println(document.content());
    return document;
}

}

The XML file: https://data.oregon.gov/api/views/j8eb-8um2/rows.xml?accessType=DOWNLOAD However, the output is:

[org.dom4j.tree.DefaultElement@50e96ea1 [Element: <response attributes: []/>]]
0

So what's wrong with that?

1

There are 1 answers

0
Chen On

All right, I got the reason. I confused the root element in the XML file. It is "response", not "rows". Thanks anyway :)