开发者

Java file uri with xml file null pointer exception [closed]

开发者 https://www.devze.com 2023-03-12 00:42 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I am using windows OS, and want to parse xml file, but get null pointer error....

    public void print( )
    throws SAXException, IOException {

             DocumentBuilder builder;

   开发者_如何学Python         Document document = builder.parse( "D:\\my\\xml.xml");//null pointer exception

}

here is the solution:

public class DOMPrinter {

         private DocumentBuilder builder;


        public void print(String fileName )//, PrintStream out)
                throws SAXException, IOException {

            try
            {
                DocumentBuilderFactory fact= DocumentBuilderFactory.newInstance();

                builder= fact.newDocumentBuilder();

            Document document = builder.parse( fileName);

            Node node = document.getDocumentElement();
              String root = node.getNodeName();
              System.out.println("Root Node: " + root);

            }
            catch (Exception e) {
                // TODO: handle exception
            }
}

I didn't use DocumentBuilderFactory to create DocumentBuilder , so that was a error.


You never instantiated builder. You need to say builder = ...;

Also, you can't have private fields inside a method. Delete the private keyword.

0

精彩评论

暂无评论...
验证码 换一张
取 消