2013-07-02 34 views
2

虽然我试图获得根元素公司的属性,我发现以下问题,也有一些例外。使用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) 
+1

你需要从org.w3c.dom.Element – Inv3r53

回答

6

你有

import javax.lang.model.element.Element; 

但你要

import org.w3c.dom.Element; 

改为。

而且,有关本:

也是它做XML的解析的方式吗?有没有别的办法和 一样简单的做法?

您正在使用java提供的方式来执行xml解析。使用第三方零件库有几种更好的替代方案。我建议测试jdom,这简单得多。见示例here

+1

...“你甚至可以*两次*” –

+0

好吧..但是现在在元素元素= document.getDocument元素行,但Eclipse提示我为“添加元素”为什么?错误在哪里? – Bitopan

+0

“现在在行”? – eis

0

问题是因为这个

import javax.lang.model.element.Element; 

使用该import语句

import org.w3c.dom.Element 
+0

导入元素,那么我该怎么做?删除该导入? – Bitopan

+1

你应该简单地用'import org.w3c.dom.Element;'来代替'import javax.lang.model.element.Element;'' – mariosangiorgio