java Dom(xml序列化及CUP)
package anby.com; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.Result; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlCUP { Book book=new Book(); public static void main(String args[]) throws Exception { Document doc = getDocument(); //获取根元素 Element root=doc.getDocumentElement(); //创建子节点 Element childroot=doc.createElement("book"); //将子元素增加到根元素中 root.appendChild(childroot); NodeList nodeHead = doc.getChildNodes(); for (int i = 0; i < nodeHead.getLength(); i++) { Node childNode = nodeHead.item(i); Element ele = (Element) childNode; if ("titile".equals(ele.getElementsByTagName("id"))) { ele.setTextContent("b003");//修改节点内容 //删除子节点就代表着删除父节点 Node parent =ele.getParentNode(); parent.removeChild(ele); } } SaveXml(doc); } //将Document对象保存为xml文档 private static void SaveXml(Document doc) throws Exception { Transformer tansform = TransformerFactory.newInstance() .newTransformer(); tansform.transform(new DOMSource(doc), new StreamResult("Result.xml")); } // 从xml文件中获取Document对象的实例 public static Document getDocument() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = factory.newDocumentBuilder(); Document doc = docbuilder.parse("Book.xml"); return doc; } }
<?xml version="1.0" encoding="UTF-8"?> <Books> <book id="boo1"> <titile>呐喊</titile> <price>18</price> </book> <book id="boo2"> <titile>彷徨</titile> <price>15</price> </book> </Books>