DOM-XML(解析与创建)
/** * 读取(解析)xml文件 * @author Administrator * */ public class DOMRead { public static void main(String[] args) throws Exception{ File file=new File("e:\\contact.xml"); InputStream in=new FileInputStream(file); //创建DocuemntBuilderFactory实例化对象 DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); //通过DocumentBuilderFactory实例化对象来创建DocumentBuilder对象 DocumentBuilder db=dbf.newDocumentBuilder(); //通过DocumentBuilder实例化对象 解析方法 来获取Document对象 Document document=db.parse(in); //通过document对象来获取指定tagName的所有标签元素 NodeList memberList = document.getElementsByTagName("member"); for(int i=0;i<memberList.getLength();i++){ //获取指定索引的标签元素 Element ele =(Element) memberList.item(i); //获取标签元素的属性 String id = ele.getAttribute("id"); String name = ele.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); String phone = ele.getElementsByTagName("phone").item(0).getFirstChild().getNodeValue(); System.out.println("id="+id+",name="+name+",phone="+phone); } } } /** * 输出(创建)xml文件 * @author Administrator * */ public class DOMWrit { public static void main(String[] args) throws Exception { File outFile=new File("e:"+File.separator+"book.xml"); DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); //通过DocumentBuilder实例化对象 创建方式 来获取Document对象 Document document=db.newDocument(); //创建根节点books Element booksElement=document.createElement("books"); String[] title=new String[]{"三国演义","红楼梦","水浒传"}; Double[] price=new Double[]{99.9,88.8,77.7}; for(int i=0;i<title.length;i++){ //创建book节点 Element bookElt=document.createElement("book"); //创建title、price节点 Element titleElt=document.createElement("title"); Element priceElt=document.createElement("price"); //设置title节点的内容,需要创建文本节点 titleElt.appendChild(document.createTextNode(title[i])); //设置price节点的内容,需要创建文本节点 priceElt.appendChild(document.createTextNode(String.valueOf(price[i]))); //将title、price节点添加到book节点中 bookElt.appendChild(titleElt); bookElt.appendChild(priceElt); //将book节点添加到books根节点中 booksElement.appendChild(bookElt); } //遗忘的步骤 //将根节点设置到Document之中 document.appendChild(booksElement); //将DOM树转换为xml进行输出 TransformerFactory transformerfactory=TransformerFactory.newInstance(); Transformer transformer=transformerfactory.newTransformer(); //设置输出的元素 Source xmlSource=new DOMSource(document); Result outputTarget=new StreamResult(outFile); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); //输出 transformer.transform(xmlSource, outputTarget); } }