Bitopan
Bitopan

Reputation: 53

Parsing Xml file using Java throws Exception. Why?

While I was trying to get the attribute of the root element Company I found the following problems, also some exceptions.

But I imported everything I need; then also eclipse says that remove unused import.

I want to know that why it is happening even after i have imported everything, please give me some idea to remove the bug.

Also is it the way to do xml-parsing? is there any alternative and easy way to do the same?

import java.io.EOFException;
import java.io.File;
import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import javax.lang.model.element.Element;

public class DomTest1 {
    private static final String file = "test1.xml";

    public static void main(String[] args) {
        if (args.length>0) {
            file = args[0];
        }

        try {
            DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
            DocumentBuilder builder=factory.newDocumentBuilder();
            Document document=builder.parse(new File(file));
            Element root=document.getDocumentElement();
            System.out.println(root.getTagName());
            System.out.printf("name: %s%n", root.getAttribute("name"));
            System.out.printf("sHortname: %s%n", root.getAttribute("sHortname"));
            System.out.printf("mission : %s%n", root.getAttribute("mission"));
        } catch(EOFException e) {
            e.printStackTrace();
        }
    }
}

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Type mismatch: cannot convert from org.w3c.dom.Element to javax.lang.model.element.Element
The method getTagName() is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element
The method getAttribute(String) is undefined for the type Element

at DomTest1.main(DomTest1.java:23)

Upvotes: 2

Views: 1383

Answers (2)

eis
eis

Reputation: 53553

You have

import javax.lang.model.element.Element;

but you want

import org.w3c.dom.Element;

instead.

Also, regarding this:

also is it the way to do xml-parsing? is there any alternative and easy way to do the same?

You are using java out of the box-provided ways to do xml parsing. There are several, better alternatives using 3rd part libraries. I'd recommend testing jdom, it is a lot simpler. See example here.

Upvotes: 6

Waqas Ali
Waqas Ali

Reputation: 1652

problem is because of this

import javax.lang.model.element.Element;

use this import statement

import org.w3c.dom.Element

Upvotes: 0

Related Questions