M
Matt
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!!
=========
<?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!!