嘿,伙计们,我是Java解析领域的新手,我发现XML可能是我最好的选择,因为我需要同时读写StaX文件。好的,我有一个非常短(而且应该非常简单)的程序,它(应该)创建一个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>发布于 2012-08-21 18:53:10
您的问题必须执行w/ basic java编程,而不需要做w/ stax。FileInputStream的作用域位于try块中(一些体面的代码格式会有所帮助),因此在您试图创建XMLStreamReader的代码中不可见。带有格式:
XMLInputFactory inFactory = XMLInputFactory.newInstance();
try {
// fIS is only visible within this try{} block
FileInputStream fIS = new FileInputStream("stax.xml");
} catch (FileNotFoundException na) {
System.out.println("FileNotFound");
}
try {
// fIS is not visible here
XMLStreamReader xmlReader = inFactory.createXMLStreamReader(fIS);
} catch (XMLStreamException xmle) {
System.out.println(xmle);
}其次,StAX是一个很好的API,对于java中高性能的XML处理来说是一个很好的API。然而,它不是最简单的XML。最好从基于DOM的apis开始,只有在使用DOM遇到性能问题时才使用StAX。如果您仍然使用StAX,我建议您使用XMLEventReader而不是XMLStreamReader (同样,更容易使用的api)。
最后,不要隐藏异常细节(例如捕获它们并打印不包含异常本身的内容)或忽略它们(例如,在抛出异常后继续处理而不试图处理问题)。
https://stackoverflow.com/questions/12061125
复制相似问题