Java and XML (2) write XML read and write programs with Java

xiaoxiao2021-03-06  26

Java and XML (2) write XML read and write programs with Java

This is a Java program that reads the XML file, I call it. The XML file is read in the DOM mode to the vector. package src; import java.io *;. import java.util.Vector; import javax.xml.parsers *;. import org.w3c.dom *;. public class readxml {static Document document; private boolean validating; public readxml ( ) {} public Vector toRead (String filename) {Vector title = new Vector (); Vector content = new Vector (); String myStr = new String (); try {DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); factory.setValidating ( validating); DocumentBuilder builder = factory.newDocumentBuilder (); document = builder.parse (new File (filename)); document.getDocumentElement () normalize ();. Node node = document.getFirstChild (); NodeList list = node.getChildNodes (); For (int i = 0; i

Public static void main (string [] args) {Vector a; readxml my = new readXML (); a = my.toread ("f: t //tomcat5/WebApps//myxml//xmldata/9.xml") For (int i = 0; i

import org.w3c.dom *;. import javax.xml.parsers *;. import javax.xml.transform *;. import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io *;. public class writexml {private Document document; private String filename; public writexml (String name) throws ParserConfigurationException {filename = name; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = factory.newDocumentBuilder (); document = builder.newDocument ();} public void toWrite (String mytitle, String mycontent) {Element root = document.createElement ( "WorkShop"); document.appendChild (root); Element title = document.createElement ( "title"); title.appendChild (document.createTextNode (mytitle)); root.appendChild (title); Element content = document.createElement ( "Content"); content.appendChild (document.createTextNode (mycontent)); root.appendChild (content); } Public void TOSAVE () {Try {TransformerFactory TF = TransformerFactory.newInstance (); TransformerFactory.newinstance () former transformer = tf.newTransformer (); DOMSource source = new DOMSource (document); transformer.setOutputProperty (OutputKeys.ENCODING, "GB2312"); transformer.setOutputProperty (OutputKeys.INDENT, "yes"); PrintWriter pw = new PrintWriter ( new FileOutputStream (filename)); StreamResult result = new StreamResult (pw); transformer.transform (source, result);} catch (TransformerException mye) {mye.printStackTrace ();} catch (IOException exp) {exp.printStackTrace () }} Public static void main (string args []) {try {writexml myXML = new WriteXML ("f: t //tomcat5/WebApps//myxml//xmldata//9.xml"); myxml.towrite (" Chinese Title "," Chinese Content ");

转载请注明原文地址:https://www.9cbs.com/read-65114.html

New Post(0)