Runtime error to get the attribute value of an element

Discussion in 'Java' started by Matt, Jun 8, 2004.

  1. Matt

    Matt Guest

    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!!
     
    Matt, Jun 8, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matthet
    Replies:
    2
    Views:
    673
    Matthet
    Sep 24, 2003
  2. Replies:
    1
    Views:
    4,289
    Joe Kesselman
    Aug 2, 2006
  3. Replies:
    8
    Views:
    523
  4. PeteOlcott
    Replies:
    1
    Views:
    949
    Mukul Gandhi
    Feb 5, 2009
  5. pbd22
    Replies:
    1
    Views:
    171
    Martin Honnen
    Jul 3, 2007
Loading...

Share This Page