Discussions

General J2EE: Runtime error to get the attribute value of an element

  1. mydoc.xml
    =========
    <?xml version = "1.0"?>
    <persons>
    <person name="Joe" age="22" />
    </persons>


    In mydox.xml, I want to get the attribute values of element person. Of course,
    in the actual XML file, it is more complicated.

    However, I get the following run-time error,
    Exception in thread "main" java.lang.NullPointerException
            at ParserTest.main(ParserTest2.java:18) on line element.hasAttribute("name")
            

    import java.io.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;

    public class ParserTest2
    {
      public static void main(String[] args) throws ParserConfigurationException, SAXException
      {
    String xmlFile = "mydoc.xml";
    doc = getDocumentFromFile(xmlFile);
    Element element = doc.getElementById("person");
    //Exception in thread "main" java.lang.NullPointerException
      if (element.hasAttribute("name"))
    { System.out.println("attribute = " + element.getAttribute("name"));
    }
        }

    public static Document getDocumentFromFile(String xmlFile)
    {
    try
    {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File(xmlFile));
    return doc;
    }
    catch(IOException e)
    { e.printStackTrace();
    return null;
    }
    catch(SAXException e)
    { e.printStackTrace();
    return null;
    }
    catch(ParserConfigurationException e)
    { e.printStackTrace();
    return null;
    }
    }

    private static Document doc;
    }



    any ideas? Thanks!!
  2. The getElementById() method locations an element via an ID attribute (an attribute declared to be type ID in the DTD). Since you don't have a DTD, you have no ID attributes and getElementById() will always return a null value.

    You want to use the getElementsByTagName(), which returns a NodeList of all elements matching a given name:

    NodeList list = doc.getElementsByTagName("person");
    Element element = list.item(0); // First person tag