In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article shows you four parsing methods of xml and how to write the source code. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
This is also reproduced by myself, and now I am quite familiar with DOM. I don't just copy the code. I can try to be familiar with one or two of them. It will be useful in the future.
Four parsing methods of xml and their source code (SAX, DOM, JDOM, DOM4J)
First: SAX parsing
SAX processing mechanism: SAX is an event-driven API. Parsing XML documents with SAX involves two parts: the parser and the event handler. The parser is responsible for reading the XML document and sending events such as element start and element end events to the event handler, while the event handler is responsible for responding to the event and processing the passed XML data.
Xml file for testing: db.xml
Xml code
Oracle.jdbc.driver.OracleDriver
Jdbc:oracle:thin:@localhost:1521:oracle
Scott
Tiger
Oracle.jdbc.driver.OracleDriver
Jdbc:oracle:thin:@localhost:1521:oracle
Scott
Tiger
DTD file db.dtd
Xml code
SAX parsing example 1
Org.xml.sax.DefalutHandler class: you can extend this class to give your own parsing implementation
SAXPrinter.java
Java code
Import java.io.File; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SAXPrinter extends DefaultHandler {/ * / * document start event * / public void startDocument () throws SAXException {System.out.println (") } / * receive processing instruction event * / public void processingInstruction (String target, String data) throws SAXException {System.out.println (") } / * * / / * * element start event * Parameter description: * uri-namespace URI. If the element does not have any namespace URI or is not performing namespace processing, it is an empty string. * localName-the local name (without a prefix), or an empty string if no namespace processing is being performed. * qName-qualified name (with a prefix), or an empty string if the qualified name is not available. * attributes-attributes attached to the element. If there is no property, it will be an empty Attributes object. * / public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {System.out.print (");} / * * / / * element character data event: receive character data in element * Note: 1. Applications should not attempt to read data outside the specified range of the ch array (that is, from start to length) * 2. Some parsers will use the ignorableWhitespace () method to report white space in the content of the element, rather than the characters () method, such as: parser * / public void characters (char [] ch, int start, int length) throws SAXException {System.out.print (new String (ch,start,length)) } / * end element event * / public void endElement (String uri, String localName, String qName) throws SAXException {System.out.print (");} public static void main (String [] args) {SAXParserFactory spf=SAXParserFactory.newInstance () Try {SAXParser sp=spf.newSAXParser (); sp.parse (new File ("db.xml"), new SAXPrinter ();} catch (Exception e) {e.printStackTrace ();} import java.io.File;import javax.xml.parsers.SAXParser Import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class SAXPrinter extends DefaultHandler {/ * / * document start event * / public void startDocument () throws SAXException {System.out.println (") } / * receive processing instruction event * / public void processingInstruction (String target, String data) throws SAXException {System.out.println (") } / * * / / * * element start event * Parameter description: * uri-namespace URI. If the element does not have any namespace URI or is not performing namespace processing, it is an empty string. * localName-the local name (without a prefix), or an empty string if no namespace processing is being performed. * qName-qualified name (with a prefix), or an empty string if the qualified name is not available. * attributes-attributes attached to the element. If there is no property, it will be an empty Attributes object. * / public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {System.out.print (");} / * * / / * element character data event: receive character data in element * Note: 1. Applications should not attempt to read data outside the specified range of the ch array (that is, from start to length) * 2. Some parsers will use the ignorableWhitespace () method to report white space in the content of the element, rather than the characters () method, such as: parser * / public void characters (char [] ch, int start, int length) throws SAXException {System.out.print (new String (ch,start,length)) } / * * / * end element event * / public void endElement (String uri, String localName, String qName) throws SAXException {System.out.print (");} public static void main (String [] args) {SAXParserFactory spf=SAXParserFactory.newInstance (); try {SAXParser sp=spf.newSAXParser () Sp.parse (new File ("db.xml"), new SAXPrinter ();} catch (Exception e) {e.printStackTrace ();}
SAX parsing example 2
Org.xml.sax.ContentHandler interface: give your own parsing implementation by implementing this interface.
Org.xml.sax.ErrorHandler interface: if a SAX application needs to implement custom error handling, it must implement this interface and call the setErrorHandler () method of the XMLReader object to register the exception handling instance with the parser, so that the parser will report all errors and warnings through this interface.
ContentHandlerImpl.java
Java code
Import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; public class ContentHandlerImpl implements ContentHandler {/ * / * document start event * / public void startDocument () throws SAXException {System.out.println (") } / * receive processing instruction event * / public void processingInstruction (String target, String data) throws SAXException {System.out.println (") } / * * / / * * element start event * Parameter description: * uri-namespace URI. If the element does not have any namespace URI or is not performing namespace processing, it is an empty string. * localName-the local name (without a prefix), or an empty string if no namespace processing is being performed. * qName-qualified name (with a prefix), or an empty string if the qualified name is not available. * attributes-attributes attached to the element. If there is no property, it will be an empty Attributes object. * / public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {System.out.print (");} / * * / / * element character data event: receive character data in element * Note: 1. Applications should not attempt to read data outside the specified range of the ch array (that is, from start to length) * 2. Some parsers will use the ignorableWhitespace () method to report white space in the content of the element, rather than the characters () method, such as: parser * / public void characters (char [] ch, int start, int length) throws SAXException {System.out.print (new String (ch,start,length)) } / * end element event * / public void endElement (String uri, String localName, String qName) throws SAXException {System.out.print ("") } public void endDocument () throws SAXException {} public void endPrefixMapping (String prefix) throws SAXException {} public void ignorableWhitespace (char [] ch, int start, int length) throws SAXException {} public void setDocumentLocator (Locator locator) {} public void skippedEntity (String name) throws SAXException {} public void startPrefixMapping (String prefix String uri) throws SAXException {}} import org.xml.sax.Attributes Import org.xml.sax.ContentHandler;import org.xml.sax.Locator;import org.xml.sax.SAXException;public class ContentHandlerImpl implements ContentHandler {/ * / * document start event * / public void startDocument () throws SAXException {System.out.println (") } / * receive processing instruction event * / public void processingInstruction (String target, String data) throws SAXException {System.out.println (") } / * * / / * * element start event * Parameter description: * uri-namespace URI. If the element does not have any namespace URI or is not performing namespace processing, it is an empty string. * localName-the local name (without a prefix), or an empty string if no namespace processing is being performed. * qName-qualified name (with a prefix), or an empty string if the qualified name is not available. * attributes-attributes attached to the element. If there is no property, it will be an empty Attributes object. * / public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {System.out.print (");} / * * / / * element character data event: receive character data in element * Note: 1. Applications should not attempt to read data outside the specified range of the ch array (that is, from start to length) * 2. Some parsers will use the ignorableWhitespace () method to report white space in the content of the element, rather than the characters () method, such as: parser * / public void characters (char [] ch, int start, int length) throws SAXException {System.out.print (new String (ch,start,length)) } / * end element event * / public void endElement (String uri, String localName, String qName) throws SAXException {System.out.print ("") } public void endDocument () throws SAXException {} public void endPrefixMapping (String prefix) throws SAXException {} public void ignorableWhitespace (char [] ch, int start, int length) throws SAXException {} public void setDocumentLocator (Locator locator) {} public void skippedEntity (String name) throws SAXException {} public void startPrefixMapping (String prefix, String uri) throws SAXException {}}
ErrorHandlerImpl.java
Java code
Public class ErrorHandlerImpl implements ErrorHandler {public void warning (SAXParseException e) throws SAXException {System.out.println ("[Warning]" + getLocationString (e) + ":" + e.getMessage ());} public void error (SAXParseException e) throws SAXException {System.out.println ("[Error]" + getLocationString (e) + ":" + e.getMessage ()) } public void fatalError (SAXParseException e) throws SAXException {System.out.println ("[Fatal Error]" + getLocationString (e) + ":" + e.getMessage ());} private String getLocationString (SAXParseException e) {StringBuffer sb=new StringBuffer (); String publicId=e.getPublicId (); if (sb.append (publicId); sb.append (")) } String systemId=e.getSystemId (); if (systemIdwords null) {sb.append (systemId); sb.append ("");} sb.append (e.getLineNumber ()); sb.append (":"); sb.append (e.getColumnNumber ()); return sb.toString () 1.} public class ErrorHandlerImpl implements ErrorHandler {public void warning (SAXParseException e) throws SAXException {System.out.println ("[Warning]" + getLocationString (e) + ":" + e.getMessage ());} public void error (SAXParseException e) throws SAXException {System.out.println ("[Error]" + getLocationString (e) + ":" + e.getMessage ()) } public void fatalError (SAXParseException e) throws SAXException {System.out.println ("[Fatal Error]" + getLocationString (e) + ":" + e.getMessage ());} private String getLocationString (SAXParseException e) {StringBuffer sb=new StringBuffer (); String publicId=e.getPublicId (); if (sb.append (publicId); sb.append (");} String systemId=e.getSystemId () If {sb.append (systemId); sb.append (");} sb.append (e.getLineNumber ()); sb.append (": "); sb.append (e.getColumnNumber ()); return sb.toString ();}}
SaxParserTest.java
Java code
Import java.io.FileInputStream; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; public class SaxParserTest {public static void main (String [] args) {try {XMLReader xmlReader=XMLReaderFactory.createXMLReader (); / / close or open the authentication xmlReader.setFeature ("http://xml.org/sax/features/validation",true);") / / register the event handler xmlReader.setContentHandler (new ContentHandlerImpl ()); / / register the exception handler xmlReader.setErrorHandler (new ErrorHandlerImpl ()); xmlReader.parse (new InputSource (new FileInputStream ("saxdb.xml"));} catch (Exception e) {System.out.println (e.getMessage ()) } import java.io.FileInputStream;import org.xml.sax.InputSource;import org.xml.sax.XMLReader;import org.xml.sax.helpers.XMLReaderFactory;public class SaxParserTest {public static void main (String [] args) {try {XMLReader xmlReader=XMLReaderFactory.createXMLReader (); / / close or open the authentication xmlReader.setFeature ("http://xml.org/sax/features/validation",true);") / / register the event handler xmlReader.setContentHandler (new ContentHandlerImpl ()); / / register the exception handler xmlReader.setErrorHandler (new ErrorHandlerImpl ()); xmlReader.parse (new InputSource (new FileInputStream ("saxdb.xml"));} catch (Exception e) {System.out.println (e.getMessage ());}
The second kind: DOM parsing
The core concept in DOM is the node. When DOM parses an XML document, it maps the parts (elements, attributes, text, comments, processing instructions, and so on) that make up the XML document to an object (node). In memory, these nodes form a lesson document tree. The whole tree is a node, and each node in the tree is also a tree (subtree). It can be said that DOM is an object description of this tree. We access the contents of the XML document by visiting the nodes in the tree.
PS: an attribute node is attached to an element and cannot be regarded as a child node of an element, let alone as a separate node
DOMPrinter.java
Java code
Import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.sun.org.apache.xerces.internal.parsers.DOMParser; public class DOMPrinter {public static void main (String [] args) {try {/ * / * * get the Document object * / DOMParser parser = new DOMParser (); parser.parse ("db.xml") Document document = parser.getDocument (); printNode (document);} catch (Exception e) {e.printStackTrace ();}} public static void printNode (Node node) {short nodeType=node.getNodeType (); switch (nodeType) {case Node.PROCESSING_INSTRUCTION_NODE:// preprocessing instruction type printNodeInfo (node); break Case Node.ELEMENT_NODE:// element node type printNodeInfo (node); printAttribute (node); break; case Node.TEXT_NODE:// text node type printNodeInfo (node); break; default: break;} Node child=node.getFirstChild (); while (childbirth node null) {printNode (child) Child=child.getNextSibling ();}} / * / / * print node * @ param node * / public static void printNodeInfo (Node node) {if (node.getNodeType () = = Node.ELEMENT_NODE) {System.out.println ("NodeName:" + node.getNodeName ()) } else if (node.getNodeType () = = Node.TEXT_NODE) {String value = node.getNodeValue () .trim (); if (! value.equals (")) System.out.println (" NodeValue: "+ value); else System.out.println () } else {System.out.println (node.getNodeName () + ":" + node.getNodeValue ());}} / * * / / * print node attributes * @ param aNode node * / public static void printAttribute (Node aNode) {NamedNodeMap attrs = aNode.getAttributes () If {for (int I = 0; I < attrs.getLength ()) {Node attNode = attrs.item (I); System.out.println ("Attribute:" + attNode.getNodeName () + "=\" + attNode.getNodeValue () + "\");} import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap Import org.w3c.dom.Node;import com.sun.org.apache.xerces.internal.parsers.DOMParser;public class DOMPrinter {public static void main (String [] args) {try {/ * / * * get the Document object * / DOMParser parser = new DOMParser (); parser.parse ("db.xml"); Document document = parser.getDocument (); printNode (document) } catch (Exception e) {e.printStackTrace ();}} public static void printNode (Node node) {short nodeType=node.getNodeType (); switch (nodeType) {case Node.PROCESSING_INSTRUCTION_NODE:// preprocessing instruction type printNodeInfo (node); break; case Node.ELEMENT_NODE:// element node type printNodeInfo (node); printAttribute (node); break Case Node.TEXT_NODE:// text node type printNodeInfo (node); break; default: break;} Node child=node.getFirstChild (); while (childbirth nodes null) {printNode (child); child=child.getNextSibling () }} / * / * print node * @ param node * / public static void printNodeInfo (Node node) {if (node.getNodeType () = = Node.ELEMENT_NODE) {System.out.println ("NodeName:" + node.getNodeName ());} else if (node.getNodeType () = = Node.TEXT_NODE) {String value = node.getNodeValue (). Trim () If (! value.equals (")) System.out.println (" NodeValue: "+ value); else System.out.println ();} else {System.out.println (node.getNodeName () +": "+ node.getNodeValue ()) }} / * / * print node attributes * @ param aNode node * / public static void printAttribute (Node aNode) {NamedNodeMap attrs = aNode.getAttributes (); if (attrsprinting nodes null) {for (int I = 0; I < attrs.getLength (); iNode +) {Node attNode = attrs.item (I) System.out.println ("Attribute:" + attNode.getNodeName () + "=\" + attNode.getNodeValue () + "\");}}
DOM generates XML document: DOMCreateExample.java
Java code
Import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.sun.org.apache.xml.internal.serialize.XMLSerializer Public class DOMCreateExample {public static void main (String [] args) throws ParserConfigurationException {/ / DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation (); DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = builderFact.newDocumentBuilder (); Document doc = builder.newDocument (); / / Document doc = domImp.createDocument (null, null, null); Element root = doc.createElement ("games"); Element child1 = doc.createElement ("game") Child1.appendChild (doc.createTextNode ("Final Fantasy VII")); child1.setAttribute ("genre", "rpg"); root.appendChild (child1); doc.appendChild (root); XMLSerializer serial; try {serial = new XMLSerializer (new FileOutputStream ("domcreate.xml"), null); serial.serialize (doc) } catch (FileNotFoundException E1) {e1.printStackTrace ();} catch (IOException e) {e.printStackTrace ();} import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element Import com.sun.org.apache.xml.internal.serialize.XMLSerializer;public class DOMCreateExample {public static void main (String [] args) throws ParserConfigurationException {/ / DOMImplementation domImp = DOMImplementationImpl.getDOMImplementation (); DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance (); DocumentBuilder builder = builderFact.newDocumentBuilder (); Document doc = builder.newDocument (); / / Document doc = domImp.createDocument (null, null, null); Element root = doc.createElement ("games"); Element child1 = doc.createElement ("game") Child1.appendChild (doc.createTextNode ("Final Fantasy VII")); child1.setAttribute ("genre", "rpg"); root.appendChild (child1); doc.appendChild (root); XMLSerializer serial; try {serial = new XMLSerializer (new FileOutputStream ("domcreate.xml"), null); serial.serialize (doc);} catch (FileNotFoundException E1) {e1.printStackTrace () } catch (IOException e) {e.printStackTrace ();}
The third kind of JDOM analysis
JDOM makes use of the excellent features of java language, which greatly simplifies the processing of XML documents, and is easier to use than DOM. JDOM also uses object trees to represent XML documents, and JDOM uses SAXj parsers to analyze XML documents and build JDOM trees. However, JOMD itself does not provide a parser, it uses the standard SAX parser provided by other developers. JDOM selects the parser by default through JAXP, which can be set by manually knowing the parser's class name.
The first step is to add the jar package of jdom to the project, where jdom1.0.jar is used. (see Annex)
JDOMConvert.java
Java code
Import java.io.File; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class JDOMConvert {public static void main (String [] args) {SAXBuilder saxBuilder=new SAXBuilder (); try {Document doc=saxBuilder.build (new File ("domdb.xml")) / / first create the node Element eltDb=new Element ("db"); Element eltDriver=new Element ("driver"); Element eltUrl=new Element ("url"); Element eltUser=new Element ("user"); Element eltPassword=new Element ("password"); / / set the value of the node eltDriver.setText ("com.mysql.jdbc.Driver") EltUrl.setText ("jdbc:mysql://localhost/mySql"); eltUser.setText ("root"); eltPassword.setText ("xlc"); / / add to the root node eltDb.addContent (eltDriver); eltDb.addContent (eltUrl); eltDb.addContent (eltUser); eltDb.addContent (eltPassword) / / the root node sets properties eltDb.setAttribute ("type", "mysql"); Element root=doc.getRootElement (); / root.removeChild ("db"); / / deletes the node root.addContent (eltDb); / / adds the node / / modifies the content root.getChild ("db"). GetChild ("user"). SetText ("system") in the db node. Root.getChild ("db") .getChild ("password") .setText ("manager"); XMLOutputter xmlOut=new XMLOutputter (); / set XML format Format fmt=Format.getPrettyFormat (); fmt.setIndent ("); fmt.setEncoding (" utf-8 ") XmlOut.setFormat (fmt); xmlOut.output (doc,System.out);} catch (Exception e) {e.printStackTrace ();} import java.io.File;import org.jdom.Document;import org.jdom.Element;import org.jdom.input.SAXBuilder;import org.jdom.output.Format Import org.jdom.output.XMLOutputter;public class JDOMConvert {public static void main (String [] args) {SAXBuilder saxBuilder=new SAXBuilder (); try {Document doc=saxBuilder.build (new File ("domdb.xml")); / / first create the node Element eltDb=new Element ("db"); Element eltDriver=new Element ("driver"); Element eltUrl=new Element ("url") Element eltUser=new Element ("user"); Element eltPassword=new Element ("password"); / / set the value of the node eltDriver.setText ("com.mysql.jdbc.Driver"); eltUrl.setText ("jdbc:mysql://localhost/mySql"); eltUser.setText ("root"); eltPassword.setText ("xlc"); / / add to the root node eltDb.addContent (eltDriver) EltDb.addContent (eltUrl); eltDb.addContent (eltUser); eltDb.addContent (eltPassword); / / Root node setting properties eltDb.setAttribute ("type", "mysql"); Element root=doc.getRootElement (); / / root.removeChild ("db"); / / Delete node root.addContent (eltDb) / / add a node / / modify the content in the db node root.getChild ("db"). GetChild ("user"). SetText ("system"); root.getChild ("db"). GetChild ("password"). SetText ("manager"); XMLOutputter xmlOut=new XMLOutputter (); / set XML format Format fmt=Format.getPrettyFormat () Fmt.setIndent (""); fmt.setEncoding ("utf-8"); xmlOut.setFormat (fmt); xmlOut.output (doc,System.out);} catch (Exception e) {e.printStackTrace ();}
JDOM generates XML document: JDOMCreate.java
Java code
Import java.io.IOException; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; public class JDOMCreate {public static void main (String [] args) {Document doc = new Document (new Element ("games")); Element newGame = new Element ("game"). SetText ("Final Fantasy VI"); doc.getRootElement (). AddContent (newGame); newGame.setAttribute ("genre", "rpg") XMLOutputter domstream = new XMLOutputter (); try {domstream.output (doc, System.out);} catch (IOException e) {e.printStackTrace ();} import java.io.IOException;import org.jdom.Document;import org.jdom.Element;import org.jdom.output.XMLOutputter Public class JDOMCreate {public static void main (String [] args) {Document doc = new Document ("games"); Element newGame = new Element ("game"). SetText ("Final Fantasy VI"); doc.getRootElement (). AddContent (newGame); newGame.setAttribute ("genre", "rpg"); XMLOutputter domstream = new XMLOutputter (); try {domstream.output (doc, System.out) } catch (IOException e) {e.printStackTrace ();}
Fourth: DOM4J parsing
Dom4j, like JDOM, is an open source XML framework for parsing XML documents. Dom4j is also used on the java platform. Dom4j API uses the java collection framework and fully supports DOM, SAX, and JAXP. Unlike JDOM, dom4j uses interfaces and abstract classes, and although dom4j's API is relatively complex, it provides more flexibility than JDOM. Dom4j also uses SAX parsers to parse XML documents and create dom4j trees. In addition, dom4j can also receive content in DOM format and provide an output mechanism from the dom4j tree to the SAX event stream or W3C DOM tree. Unlike JDOM, dom4j comes with a SAX parser Aelfred2. If the SAX parser is not set up and the parser is not set through the system property org.xml.sax.driver, dom3j will use JAXP to load the parser configured by JAXP, and if it fails to create the parser, then finally use the Aelfred2 parser that comes with dom4j.
Again, the first step is to add the jar package for dom4j to the project, where dom4j-1.6.1.jar is used. (see Annex)
Dom4j generates XML document db.xml:Dom4jCreate.java
Java code
Import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class Dom4jCreate {public static void main (String [] args) {Document doc = DocumentHelper.createDocument (); doc.addProcessingInstruction ("xml-stylesheet", "type='text/xsl' href='db.xsl'") Doc.addDocType ("dbconfig", null, "db.dtd"); / / Element root=DocumentHelper.createElement ("dbconfig"); / / doc.setRootElement (root); Element root= doc.addElement ("dbconfig"); Element eltDb= root.addElement ("db"); Element eltDriver = eltDb.addElement ("driver"); Element eltUrl = eltDb.addElement ("url"); Element eltUser = eltDb.addElement ("user") Element eltPassword = eltDb.addElement ("password"); eltDriver.setText ("com.mysql.jdbc.Driver"); eltUrl.setText ("jdbc:mysql://localhost/mySql"); eltUser.setText ("root"); eltPassword.setText ("xlc"); eltDb.addAttribute ("type", "mysql") Try {/ / set output format OutputFormat outFmt = new OutputFormat (", true); outFmt.setEncoding (" UTF-8 "); / * / / * PrintWriter pw = new PrintWriter (System.out); doc.write (pw); pw.flush (); pw.close () * / XMLWriter xmlWriter=new XMLWriter (System.out, outFmt); / / XMLWriter xmlWriter=new XMLWriter (new FileWriter ("db.xml"), outFmt); xmlWriter.write (doc); xmlWriter.flush (); xmlWriter.close ();} catch (IOException e) {e.printStackTrace ();}} import java.io.IOException;import org.dom4j.Document Import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class Dom4jCreate {public static void main (String [] args) {Document doc = DocumentHelper.createDocument (); doc.addProcessingInstruction ("xml-stylesheet", "type='text/xsl' href='db.xsl'"); doc.addDocType ("dbconfig", null, "db.dtd"); / / Element root=DocumentHelper.createElement ("dbconfig") / / doc.setRootElement (root); Element root = doc.addElement ("dbconfig"); Element eltDb= root.addElement ("db"); Element eltDriver = eltDb.addElement ("driver"); Element eltUrl = eltDb.addElement ("url"); Element eltUser = eltDb.addElement ("user"); Element eltPassword = eltDb.addElement ("password"); eltDriver.setText ("com.mysql.jdbc.Driver"); eltUrl.setText ("jdbc:mysql://localhost/mySql") EltUser.setText ("root"); eltPassword.setText ("xlc"); eltDb.addAttribute ("type", "mysql"); try {/ / set the output format OutputFormat outFmt = new OutputFormat ("", true); outFmt.setEncoding ("UTF-8"); / * / * PrintWriter pw = new PrintWriter (System.out); doc.write (pw); pw.flush () Pw.close (); * / XMLWriter xmlWriter=new XMLWriter (System.out, outFmt); / / XMLWriter xmlWriter=new XMLWriter (new FileWriter ("db.xml"), outFmt); xmlWriter.write (doc); xmlWriter.flush (); xmlWriter.close ();} catch (IOException e) {e.printStackTrace ();}
Dom4j modifies XML document db.xml:Dom4jModify.java
Java code
Import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Dom4jModify {public Document modifyDocument (File inputXml) {try {SAXReader saxReader = new SAXReader (); Document document = saxReader.read (inputXml) Document.addDocType ("dbconfig", null, "db.dtd"); List list = document.content (); / / Iterator iter = document.nodeIterator (); Iterator iter = list.iterator (); Element element = (Element) iter.next (); element.element ("db"). Attribute ("type"). SetValue ("mysql") Element.element ("db"). Element ("url"). SetText ("jdbc:mysql://localhost/mySql"); element.element ("db"). Element ("driver"). SetText ("com.mysql.jdbc.Driver"); element.element ("db"). Element ("user"). SetText ("root"); element.element ("db"). Element ("password"). SetText ("xlc") / / set output format OutputFormat outFmt = new OutputFormat (", true); outFmt.setEncoding (" UTF-8 "); XMLWriter xmlWriter=new XMLWriter (new FileWriter (" domdb-modified.xml "), outFmt); xmlWriter.write (document); xmlWriter.flush (); xmlWriter.close (); return document } catch (Exception e) {System.out.println (e.getMessage ()); return null;}} public static void main (String [] args) throws Exception {Dom4jModify dom4jParser = new Dom4jModify (); Document document = dom4jParser.modifyDocument (new File ("domdb.xml")); OutputFormat outFmt = new OutputFormat ("", true) OutFmt.setEncoding ("UTF-8"); XMLWriter xmlWriter = new XMLWriter (System.out,outFmt); xmlWriter.write (document); xmlWriter.flush (); xmlWriter.close ();}} these are the four parsing methods of xml and how to write the source code. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.