Search code examples
javabukkit

Not returning correct value in xml file?


I'm trying to get a value from an XML file for a project i'm working on but i cant seem to get it...

This is the XML file:

XML file code

I tried using

    public static String getString(File file, String element) {
    try {
        File fXmlFile = file;
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getElementsByTagName(element);

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                return eElement.getElementsByTagName("author").item(0).getTextContent();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "Error";
}

Using this method to access it

File mapdata = new File(HeroVsVilliansCore.getPlugin().getDataFolder(), File.separator + "Maps" + File.separator);
         File f = new File(mapdata, "Test.xml");

But it returns "Error" and not the value of "author"?


Solution

  • Try using getDocumentElement instead of the first getElementsByTagName (by the way what's the value of element - should be "map"):

    return doc.getDocumentElement ()
          .getElementsByTagName("author")
          .item(0).getTextContent();
    

    Or split to several statements and chech that the elements have really non zero size.