xml文档的解析有两种方式: 一是DOM解析,一是SAX我们用的是dom4j的解析包,其对DOM和SAX都支持解析.
java自带以下是DOM解析.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("src/students.xml");DOM4J获取Document对象:SAXReader reader = new SAXReader(); Document doc = reader.read("src/students.xml");.............................................................................................................................
java自带SAX的解析:
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse("src/students.xml",new DefaultHandler()); DefaultHandler-->需要创建实现这个DefaultHandler接口的实现类Dom4j通过SAX获得document对象:
SAXReader reader = new SAXReader();
Document doc = reader.read(input); input------>读取xml文件的内容
..............................................................................................................................................................................
回显或写入xml内容
OutputFormat format = OutputFormat.createPRettyPrint();
//设置输出编码
format.setEncoding(
"UTF-8"
);
//创建需要写入的File对象
File file =
new
File(
"D:"
+ File.separator +
"books.xml"
);
//生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
XMLWriter writer =
new
XMLWriter(
new
FileOutputStream(file), format);
//开始写入,write方法中包含上面创建的Document对象
writer.write(doc);
..............................................................................................................................................................................
另外, dom4j支持xpath的(查询)操作.
dom4j的下载地址为: https://sourceforge.net/projects/dom4j/files/dom4j/
新闻热点
疑难解答