虽然我试图获得根元素公司的属性,我发现以下问题,也有一些例外。使用Java解析Xml文件引发异常。为什么?
但我输入了我需要的所有东西;那么也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 – Inv3r53