[英]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.