任务:读取一个没有root element的xml文件里的内容。
(本来是要读取jboss 里定义好了的queue,但实在不知道有什么方法可以采用,只好直接读取自定义的xml文件了)
翻阅了很多资料,java里对xml文件的读取大抵采用SAX,dom或者jdom方式。但无论用那种方法,在读取xml文件,生成一个Document 对象时均报错。
在相关xml文献里发现,xml的规范语法是需要包含一个root element的,而我需要读取的文档则没有写入root element。怎么办?
寻思了半天,想了个巨笨的方法,暂时先把文件转成inputstream读入内存,然后在字符串里人为加上一个根节点。最后利用普通解析xml文件的方法解析这段数据流。程序代码如下:
public string[] readXMLFile() throws javax.xml.parsers.ParserConfigurationException,
org.xml.sax.SAXException, java.io.IOException {//将文件转换为字符串,然后添上root element
String fileName = "test.xml";
FileReader fileIn = new FileReader(fileName);
BufferedReader buf=new BufferedReader(fileIn);
StringBuffer rets = new StringBuffer();
String s = "";
while(( s = buf.readLine()) != null){
rets.append(s+"\n");
s="";
}
buf.close();
fileIn.close();
String tmpXMLString = "<tmproot>" + rets.toString() + "</tmproot>";//构建 document object ,并读取节点内容,并讲queue名称存入queueList中
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(tmpXMLString)));
NodeList idents =doc.getElementsByTagName("queue");
Node tmpNode = null;
int queueCount = idents.getLength();
String[] queueList = new String[queueCount];
for ( int i = 0 ; i < queueCount; i ++ ) {
queueList[i] = idents.item(i).getTextContent();// SE v1.5//queueList[i] = tmpNode.getChildNodes().item(0).getNodeValue(); //SE v1.4
}return queueList;
}
暂时记录一下 ,等找到更合适的方法再替换。