Java uses Dom, sax, JDOM, and dom4j to operate XML

Source: Internet
Author: User

Note: Some of the comments are read/write files (corresponding to the operation string only), or the replaceable method. In JDOM and dom4j, jaxen. jar is required for xpath.

I. Dom operations

public static void getDoc() throws ParserConfigurationException, SAXException, IOException{DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();//Document doc = db.parse(new File("student.xml"));String xml = "";//xml stringDocument doc = db.parse(new InputSource(new StringReader(xml)));Element element  = doc.getDocumentElement();parseDoc(element);}public static void parseDoc(Node element){System.out.print("<");System.out.print(element.getNodeName());NamedNodeMap al = element.getAttributes();for(int i = 0 ; i < al.getLength();i++){Node node = al.item(i);System.out.print("  ");System.out.print(node.getNodeName());System.out.print("='");System.out.print(node.getNodeValue());System.out.print("'");}System.out.print(">");NodeList nl = element.getChildNodes();for(int i = 0 ;  i < nl.getLength();i++){Node node = nl.item(i);if(node.getNodeType() == Node.ELEMENT_NODE){parseDoc(node);}else if(node.getNodeType() == Node.TEXT_NODE){System.out.print(node.getNodeValue());}}System.out.print("</");System.out.print(element.getNodeName());System.out.print(">");}

Ii. Sax operations

/** * @param args * @throws SAXException  * @throws ParserConfigurationException  * @throws IOException  */public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException{SAXParserFactory saxFactory = SAXParserFactory.newInstance();SAXParser saxParser = saxFactory.newSAXParser();//saxParser.parse(new File("student.xml"), new Handler());String xml = "";//xml StringInputSource   is=new   InputSource(new   StringReader(xml)); saxParser.parse(is,  new Handler());}}class Handler extends DefaultHandler{@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException{System.out.print("<");System.out.print(qName);for(int i = 0 ; i < attributes.getLength();i++){String name = attributes.getQName(i);String value = attributes.getValue(i);System.out.print(" "+name + "='" + value+"'");}System.out.print(">");}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException{System.out.print(new String(ch,start,length));}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException{System.out.print("</");System.out.print(qName);System.out.print(">");}

Iii. JDOM operations

/*** @ Param ARGs * @ throws ioexception * @ throws filenotfoundexception * @ throws jdomexception */public static void main (string [] ARGs) throws filenotfoundexception, ioexception, jdomexception {document DOC = new document (); Doc = Doc. addcontent (new element ("student register"); element = Doc. getrootelement (); element. addcontent (new element ("student "). setattribute (new attribute ("student ID", "1 ")). addcontent (new element ("name "). settext ("Zhang San ")). addcontent (new element ("gender "). settext ("male ")). addcontent (new element ("Age "). settext ("20"); xmloutputter out = new xmloutputter (); // out. output (Doc, new fileoutputstream ("student. XML "); stringwriter Sw = new stringwriter (); out. output (Doc, SW); string xml = Sw. tostring (); saxbuilder = new saxbuilder (); // document doc1 = saxbuilder. build (new file ("student. XML "); document doc1 = saxbuilder. build (New stringreader (XML); element root = doc1.getrootelement (); print (Root);/*** XPath, you need to add jaxen. jar package */list <element> elements = XPath. selectnodes (root, "// name"); system. out. println (elements);} public static void print (element) {system. out. println (element); List <element> elements = element. getchildren (); For (Element E: Elements) {print (e );}}

Iv. dom4j Operation Method

/*** @ Param ARGs * @ throws ioexception * @ throws define entexception */public static void main (string [] ARGs) throws ioexception, incluentexception {element = incluenthelper. createelement ("student register"); document DOC = incluenthelper. createdocument (element); element stu_element = element. addelement ("student"); stu_element.addattriement ("student ID", "1"); element name_element = stu_element.addelement ("name"); name_eleme NT. settext ("Zhang San"); element sex_element = stu_element.addelement ("gender"); sex_element.settext ("male"); element age_element = stu_element.addelement ("Age "); age_element.settext ("20"); outputformat of = new outputformat ("", true); stringwriter Sw = new stringwriter (); xmlwriter = new xmlwriter (SW, of); xmlwriter. write (DOC); string xml = Sw. tostring (); system. out. println (XML); // xmlwriter = new xmlw Riter (New fileoutputstream ("dom4j_student.xml"), of); // xmlwriter. write (DOC); saxreader = new saxreader (); document doc1 = saxreader. read (New stringreader (XML); // document doc1 = saxreader. read (New fileinputstream ("dom4j_student.xml"); print (doc1.getrootelement ();/*** XPath, you need to add jaxen. jar package */list <? Extends node> elements = Doc. selectnodes ("// name"); // XPath = new defaultxpath ("// name"); // list <? Extends node> elements = XPath. selectnodes (element); system. out. println (elements);} public static void print (element) {system. out. println (element); List <element> elements = element. elements (); For (Element E: Elements) {print (e );}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.