首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

XML 解析 解析XML有两种根本方式

2012-10-31 
XML 解析 解析XML有两种基本方式XML 解析org.w3c.dom.Document doc javax.xml.parsers.DocumentBuilderF

XML 解析 解析XML有两种基本方式
XML 解析org.w3c.dom.Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(“fileName”));doc.getDocumentElement().childNodes().item(0);?
可以看到对dom树操作就类似于在javascript里用dom api操作xml了,事实上,两者都是有w3c标准化组织提供的。

文件存放xml Document对象。
javax.xml.transform.Transformer tf =javax.xml.transform.TransformerFactory.newInstance().newTransformer();tf.transform(new javax.xml.transform.dom.DOMSource(doc),new javax.xml.transform.stream.StreamResult(new FileOutputStream(fileName)));/***将dom树对象 doc存入fileName提定的文件中**/public void saveToFile(Document doc, String fileName) throws TransformerFactoryConfigurationError, FileNotFoundException, TransformerException{ javax.xml.transform.Transformer trans = javax.xml.transform.TransformerFactory.newInstance().newTransformer(); trans.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(new FileOutputStream(fileName))); }/***生成一个带根结点名为 rootName的Dom树对象。**/public Document createXMLDoc(String rootName) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException{ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); doc.appendChild(doc.createElement(rootName)); return doc; }/***由给定文件名的xml文件生成一个Dom 树。*/public Document createXMLFromFile(String fileName) throws SAXException, IOException, ParserConfigurationException { File xmlFile = new File(fileName); if (!xmlFile.exists()) { System.err.println("File " + fileName + "doesn't exist!"); System.exit(0); } return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( fileName); }
?

热点排行