在Java应用程序中读取XML文件?

时间:2019-04-02 10:44:56

标签: java xml

在Java应用程序中读取XML文件?

doc.getDocumentElement().normalize();

我遇到错误:

"Syntax error on token "getDocumentElement", Identifier expected after this token"

这是完整的代码:

package SalesForce_Common;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class ReadDataFromXmlFile {

     File fXmlFile = new File("/Users/mkyong/staff.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("staff");
        System.out.println("----------------------------");
}}

2 个答案:

答案 0 :(得分:1)

语法错误意味着从编译器的角度来看您的代码不正确,因此我们需要完整的代码段以帮助您。

答案 1 :(得分:0)

您不能直接在Java类中编写代码。您需要将其包装在一个方法中。就您而言,您似乎想要main

public class ReadDataFromXmlFile throws IOException, SAXException, ParserConfigurationException {

  public static void main (String[] args) {
    File fXmlFile = new File("/Users/mkyong/staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("----------------------------");
  }

}