繁体   English   中英

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

[英]read an XML file in Java application?

在 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("----------------------------");
}}

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

您不能直接在 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("----------------------------");
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM