【发布时间】:2013-07-02 12:47:57
【问题描述】:
当我试图获取根元素 Company 的属性时,我发现了以下问题,还有一些异常。
但是我进口了我需要的一切;然后eclipse也说删除未使用的导入。
我想知道为什么即使在我导入所有内容之后也会发生这种情况, 请给我一些想法来消除这个错误。
这也是进行 xml 解析的方法吗?有没有其他简单的方法可以 做同样的事情吗?
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)
【问题讨论】:
-
你需要从 org.w3c.dom.Element 导入元素
标签: java xml xml-parsing