如何在Java中以编程方式读取XML元素?

时间:2015-08-07 10:57:17

标签: java xml

我正在研究如何在java中读取xml文件.Below是我的xml代码

<path>
    <Excelpath>
        C:/Documents and Settings/saalam/Desktop/Excel sheets/New Microsoft Excel Worksheet (3).xls
    </Excelpath>
</path>

使用这个,我写了java代码来读取这个xml,下面是我的java代码

try {
    //Using factory get an instance of document builder
    DocumentBuilder db = dbf.newDocumentBuilder();

    //parse using builder to get DOM representation of the XML file
    Document doc = db.parse(fXmlFile);
    //read the xml node element
    doc.getDocumentElement().normalize();
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    System.out.println("expath is:"+doc.getElementsByTagName("Excelpath"));
} catch(ParserConfigurationException pce) {
    pce.printStackTrace();
} catch(SAXException se) {
    se.printStackTrace();
} catch(IOException ioe) {
    ioe.printStackTrace();
}

}

这里我想要实现的是,我需要从xml读取xml我需要获取我提供的excelpath.later on我需要使用这个excelpath并使用它来获取我的进一步代码的excelsheet值。当我试图运行以下代码时,它没有给我选项来运行它作为Java应用程序而不是它显示“运行配置”。这是正确的,它显示为“运行配置”而不是“作为Java应用程序运行”。

1 个答案:

答案 0 :(得分:1)

根据您的问题,我假设您正在使用eclipse IDE进行开发。 Eclipse IDE基本上会显示两个不同的选项&#34;运行配置&#34;并运行作为&#34; Java应用程序&#34;。

选项&#34; Java Application&#34;当您尝试执行具有&#34; main&#34;的类时,将显示方法,它将使用默认的JVM参数运行,其他选项&#34;运行配置&#34;将始终显示,在这种情况下,您已指定您的主类,JVM参数和您的程序所依赖的其他参数(如果有)。

如果您的代码没有主要方法,请在主要课程中添加一个。

API getElementsByTagName(<<Tag Name>>)将返回具有匹配标记名称的所有节点的列表。您必须迭代节点列表并获取文本内容,如下所示。

NodeList nodeList = doc.getElementsByTagName("Excelpath");
for (int index = 0; index < nodeList.getLength(); index++) {
        System.out.println(nodeList.item(index).getTextContent());
}

请阅读此处的文档 - https://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#getElementsByTagName%28java.lang.String%29

相关问题