Calling method on Document interface in Java

2019-09-01 04:57发布

问题:

I am trying to parse an XML file in Java and after getting the DocumentBuilder object, I call the parse method on it to get a Document object. e.g. Document dom = docbuild.parse(fileName);

Then to get the root of the XML file, I use the method dom.getDocumentElement();. Since Document is an interface as defined in the javadocs, how are we able to call a method on it without defining it first?

My main objective is to create a class that inherits the Document interface, so I have to implement it. How do I go about doing this?

回答1:

DocumentBuilder returns some implementation of Document. You don't have to worry about implementing the Document interface, somebody has already done that for you. The returned document will represent the XML document, which is what you want.



回答2:

The use of the document is as follow:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse("StringOfTheSource");

These tree steps will fix your problem.