大家好,我是 Java-XML 解析领域的新手,发现 StaX API 可能是我最好的选择,因为我需要读取和写入 XML 文件。好的,所以我有一个非常短(并且应该非常简单)的程序,它(应该)创建一个 XMLInputFactory 并使用它来创建一个 XMLStreamReader。XMLStreamReader 是使用附加到与源文件相同目录中的 XML 文件的 FileInputStream 创建的。然而,即使正确编译了 FileInputStream,XMLInputFactory 也无法访问它,并且如果没有 FileInputStream,它也无法创建 XMLStreamReader。请帮忙,因为我不知道该做什么,并且沮丧到要放弃!
import javax.xml.stream.*;
import java.io.*;
public class xml {
static String status;
public static void main(String[] args) {
status = "Program has started";
printStatus();
XMLInputFactory inFactory = XMLInputFactory.newInstance();
status = "XMLInputFactory (inFactory) defined"; printStatus();
try { FileInputStream fIS = new FileInputStream("stax.xml"); }
catch (FileNotFoundException na) { System.out.println("FileNotFound"); }
status = "InputStream (fIS) declared"; printStatus();
try { XMLStreamReader xmlReader = inFactory.createXMLStreamReader(fIS); } catch (XMLStreamException xmle) { System.out.println(xmle); }
status = "XMLStreamReader (xmlReader) created by 'inFactory'"; printStatus();
}
public static void printStatus(){ //this is a little code that send notifications when something has been done
System.out.println("Status: " + status);
}
}
如果需要,这里还有 XML 文件:
<?xml version="1.0"?>
<dennis>
<hair>brown</hair>
<pants>blue</pants>
<gender>male</gender>
</dennis>