Java:使用DOM4j来实现读写XML文件中的属性和元素
DOM4可以读取和添加XML文件的属性或者元素
读取属性:
public static void ReadAttributes() throws DocumentException { File file = new File("D:\\cmz\\java\\XMLTest\\Customertest.xml"); SAXReader reader = new SAXReader(); Document doc = reader.read(file); Element root = doc.getRootElement(); try { for (Iterator iterator = root.elementIterator(); iterator.hasNext();) { Element element = (Element) iterator.next(); String CustomerID = element.attributeValue("CustomerID"); System.out.println("CustomerID = " + CustomerID); String CompanyName = element.attributeValue("CompanyName"); System.out.println("CompanyName = " + CompanyName); System.out.println("ContactName = " + element.attributeValue("ContactName")); System.out.println("ContactTitle = " + element.attributeValue("ContactTitle")); System.out.println("Address = " + element.attributeValue("Address")); System.out.println("City = " + element.attributeValue("Cit阿y")); System.out.println("PostalCode = " + element.attributeValue("PostalCode")); System.out.println("Country = " + element.attributeValue("Country")); System.out .println("Phone = " + element.attributeValue("Phone")); System.out.println("Fax = " + element.attributeValue("Fax")); System.out .println("--------------------------------------------------------\t"); } } catch (Exception e) { // TODO: handle exception } }
读取元素:
写入属性:
写出元素:
可以修改属性的文本内容: