Use Java and JAXP to access XML documents

Source: Internet
Author: User

XML series: use Java and JAXP to access and operate XML documents

1. Access XML documents using Java
Import the java. xml. parsers package and the org. W3C. Dom package
 
The Org. W3C. Dom package contains the definition of the DOM parser interface type.
 
1. Obtain the java. xml. parsers. documentbuilder class.: Provides interfaces for loading and analyzing XML documents, that is, XML analysis program interfaces.
You can configure JAXP into different XML analysis programs. java. xml. parsers. documentbuilderfactory is used to obtain an example of an analysis program.
Use documentbuilderfactory to instantiate a documentbuilder object for the current XML analysis program.
Documentbuilderfactory factory = documentbuilderfactory. newinsrance ();
Documentbuilder builder = factory. newdocumentbuilder ();
 2. Load and analyze XML documents,If the load is successful, an org. W3C. Dom. Document Object is returned,
This object represents the tree structure of the XML document in memory. If it fails, a saxexception is thrown.
A document object consists of objects that implement the node interface and its classes.

File file = new file ("type. xml ");
Document Doc = builder. parse (File );

 3. The getdocumentelement method of the Document Object obtains the Root Node object. The gettagname method returns the label name of the node..

Element root = Doc. getdocumentelement ();
String rootname = Doc. gettagname ();

 
 4. The getchildnodes method of the Element Object obtains the child element of the element and returns the nodelist set.
Getelementbytagname or getelementbyid. The child element set of the element is obtained by specifying the element name or ID. The returned result is the nodelist set.
Nodelist children = root. getchildnodes ();
Or
Nodelist children = root. getelementbytagname ("type ");
Use the item method to traverse the set. getlength provides the total number of elements in the set.

Traverse the nodelist set:
Element E = NULL;
For (INT I = 0; I <children. getlength (); I ++)
{
Node child = children. item (I );
E = (element) child;
System. Out. println (E. gettagname () + ":" + E. getfirstchild (). getnodevalue ());
}

Traverse the nodelist set:Obtain only child elements and use the instanceof operator for type check.

For (INT I = 0; I <children. getlength (); I ++)
{
Node child = children. item (I );
If (Child instanceof element)
{
Element E = (element) child;
System. Out. println (E. gettagname () + ":" + E. getnodevalue ());
}
}
Traverse the nodelist set:
Obtain the first getfirstchild method of the current node and the getnextchild method of the next subnode. If no node exists, null is returned.
For (node childnode = children. getfirstchild (); childnode! = NULL;
Childenode = childnode. getnextchild ){
If (childnode instanceof element ){
.....;
}
}
 5. The getattributes method of the element obtains the attribute set of the element. The returned result is a namednodemap object.
You can traverse namednodemap just like you can traverse the nodelist set.
Namednodemap attributes = root. getattributes ();

 Traverse the namednodemap set:
For (INT I = 0; I <attributes. getlength (); I ++)
{
Node attribute = attributes. item (I );
String attributename = attribute. getnodename ();
String attributevalue = attribute. getnodevalue ();
}

Example:
XML document (type. XML ):

<? XML version = "1.0" encoding = "UTF-8"?>
<Type xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: nonamespaceschemalocation = "type1.xsd">
<Student state = "true">
<Info>
<Name> Zhang San </Name>
<Sex> male </sex>
</INFO>
<Grede>
<Chinese> 1 </Chinese>
<Math> 119 </Math>
</Grede>
</Student>
<Teacher state = "true">
<Name> Li Si </Name>
<Sex> female </sex>
<Subject> mathematics </subject>
</Teacher>
</Type>
Java file:

package com.qu.read;import java.io.File;import java.io.IOException;import javax.xml.parsers.*;import org.w3c.dom.Attr;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class ReadXML { public ReadXML() {  } public Document readXMLFile(String fileName) {  DocumentBuilderFactory factory =     DocumentBuilderFactory.newInstance();  Document doc = null;  try {   DocumentBuilder builder = factory.newDocumentBuilder();   File file = new File(fileName);   doc = builder.parse(file);  } catch (SAXException e) {      e.printStackTrace();  }catch (IOException e){   e.printStackTrace();  }catch (ParserConfigurationException e) {      e.printStackTrace();  }  return doc;    }  public void readXMLElements(NodeList nodeList) {  NamedNodeMap attributes =  null;    for (int i = 0; i < nodeList.getLength(); i++)  {   Node childNode =  nodeList.item(i);   String str = null;   if (childNode instanceof Element){    Element child =(Element) childNode;    if( child.getChildNodes().getLength() > 1){          str = "Element :" + child.getTagName() + ";";         }else{     str = "Element :" + child.getTagName();     str += " : " + child.getFirstChild().getNodeValue() + "  ";    }    attributes = child.getAttributes();    for (int j = 0; j < attributes.getLength(); j ++)    {     Node attr = attributes.item(j);     if (attr instanceof Attr){      String attrName = attr.getNodeName();      String attrValue = attr.getNodeValue();      str += "  Attribute " + attrName + " : " + attrValue + ";";     }         }    System.out.println(str);   }     } }  public static void main(String[] args) {  ReadXML readXML = new ReadXML();  Document doc = readXML.readXMLFile("E:/workspace/ReadXML/src/com/qu/xml/type.xml");  NodeList nodeList = doc.getElementsByTagName("*");  readXML.readXMLElements(nodeList); }}

 

 


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.