XML文档可以用来进行进行数据的存储,采用的是节点的形式;从一个根节点开始向下延伸;可以对文档进行存储,添加和修改;
//创建SAXReader解析器
SAXReader reader = new SAXReader();
Document document = null;
try {
// 获取文件的Document对象,Document对象代表整个html文档,可用来访问页面中的所有元素
// Document对象是window对象的一个成员属性,通过window.document来访问,当然也可以直接使用document。
document = reader.read(ReadXml.class.getClassLoader().getResourceAsStream("day12_3/products.xml"));
} catch (DocumentException e) {
e.printStackTrace();
return;
}
Element root = document.getRootElement();//获取根节点;
List<Element> products=root.selectNodes("product");//把根节点下面的product节点放到List集合中;
for (Element e : products //遍历List集合中的products对象;
) {
//获得products中的属性;
System.out.println("产地:" + e.attributeValue("factoryaddr"));
String a = "产地:" + e.attributeValue("factoryaddr");
//找到products中的对应itemno节点;
Element itemno = (Element) e.selectSingleNode("itemno");
//获得节点之间的数值;
System.out.println("商品编号:" + itemno.getText());
String num = itemno.getText();
可以通过先获取根节点再获取下的子节点,再一步步找出节点里面的对应数值;还可以通过Xpath的方法来进行查找对应节点来继续修改;删除一样;
SAXReader reader = new SAXReader();
Document document = null;
try {
document = reader.read(ReadXml.class.getClassLoader().getResourceAsStream("day12_3/products.xml"));
} catch (DocumentException e) {
e.printStackTrace();
return;
}
Element e = (Element) document.selectSingleNode("/shop/product[itemno=" + num + "]");//可以通过/shop/product[itemno=" + num + "]来查找day12_3/products.xml中的对应product,具体是哪一个product是根据product中对应的itemno的值来确定;
e.selectSingleNode("stockcount").setText(count);//修改stockcount的值;修改完后要重新写进去;
OutputFormat of = new OutputFormat("UTF-8");
try {
//重新写进去;注意位置要是完整的地址信息;
XMLWriter xw = new XMLWriter(newFileWriter("D:\\Java01\\Zye\\src\\day12_3\\products.xml"));
xw.write(document);
xw.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
添加一个新的节点:
SAXReader reader = new SAXReader();
Document document = null;
try {
document = reader.read(ReadXml.class.getClassLoader().getResourceAsStream("day12_3/products.xml"));
} catch (DocumentException e) {
e.printStackTrace();
//判断有没有根节点,没有的话就重新生成;
document = DocumentHelper.createDocument();
document.addElement("shop");
}
//增加一个根节点(product);
Element eproduct = root.addElement("product");
//添加节点的属性;
eproduct.addAttribute("discount", discount);
eproduct.addAttribute("factoryaddr", factoryaddr);
//添加一个新节点,并设置新节点的值;
Element eitemno = eproduct.addElement("itemno");
eitemno.setText(itemnos);
//添加完成后值再写进去;
OutputFormat of = new OutputFormat("UTF-8");
try {
XMLWriter xw = new XMLWriter(new FileWriter("D:\\Java01\\Zye\\src\\day12_3\\products.xml"));
xw.write(document);
xw.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}