Java se's support for xml parsing and simple application

Source: Internet
Author: User
Tags java se

In data migration, a core process of migration is to parse and update local xml files. This operation can be completed simply by using java APIs. In javax. xml. the parsers package provides classes for processing xml files. With these classes, we can read xml files into the memory; javax. xml. the transform package provides some conversion tools. We can convert a source tree to a target tree result. For example, we can convert a dom source to an InputStream type, in this way, the xml files in the memory can be stored on the hard disk, while the xml files in the org. w3c. dom provides a DOM interface for JAVA to process XML, which can help us obtain the corresponding node, create a node, and process node attributes.

Use the javax. xml. parsers package to parse the inputstream of the xml file into a Document. The Code is as follows:
[Java]
// Package used:
Import org. w3c. dom. Document;
Import javax. xml. parsers. DocumentBuilder;
Importjavax. xml. parsers. DocumentBuilderFactory;

// Parse to document
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory. newInstance ();
DocumentBuilder docBuilder = docBuilderFactory. newDocumentBuilder ();
Document doc = docBuilder. parse (inputStream );

// Create a document
DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance ();
DocumentBuilder db = dbf. newDocumentBuilder ();
Document doc = db. newDocument ();
Node rootNode = doc. createElement ("rootNodeName ");
Doc. appendChild (rootNode );
The above content can help us Parse xml files from inputstream into DOM, or create a Document by ourselves for subsequent xml manipulation. In data migration, in addition to reading local xml files, you must be able to write the modified xml file to a specified location to import the file to the content library, in this process, javax. xml. transform and other packages.
The Transformer and TransformerFactory classes are provided in the javax. xml. transform package. The Transformer class provides the method transform (Source xmlSource, Result outputTarget), which can help us to put the xml Source in one form.
In javax. xml. the transform package defines the interfaces of source and result, while in javax. xml. transform. dom, javax. xml. transform. stream, javax. xml. transform. sax and javax. xml. transform. different implementations of source and result are implemented in stax respectively. In data migration, you need to transfer the dom in the memory to the Inputstream format and store it in the hard disk. The implementation process is as follows:
[Java]
Import javax. xml. transform. Result;
Import javax. xml. transform. Source;
Import javax. xml. transform. Transformer;
Import javax. xml. transform. TransformerFactory;
Import javax. xml. transform. dom. DOMSource;
Import javax. xml. transform. stream. StreamResult;
 
Import org. w3c. dom. Document;
 
Public InputStream toInputStream (Document doc ){
InputStream inputStream = null;
StringWriter stringWriter = null;
Try {
TransformerFactory tranFactory = TransformerFactory. newInstance ();
Transformer transformer = tranFactory. newTransformer ();
Source src = new DOMSource (doc );
StringWriter = new StringWriter ();
Result dest = new StreamResult (stringWriter );
Transformer. transform (src, dest );
 
StringBuffer sb = stringWriter. getBuffer ();
If (stringWriter! = Null ){
StringWriter. close ();
}
InputStream = new ByteArrayInputStream (sb. toString (). getBytes ("UTF-8 "));
} Catch (Exception e ){
Logger. error ("", e );
Try {
If (stringWriter! = Null)
StringWriter. close ();
If (inputStream! = Null)
InputStream. close ();
} Catch (IOException e1 ){
Logger. error ("", e );
}
}
Return inputStream;
}
The preceding section describes how to read the hard drive xml file into the memory and write it to the hard drive. Inputstream is used to read or set xml nodes and node attributes in xml operations. The following code is used for demonstration.
 
[Java]
Import org. w3c. dom. Element;
Import org. w3c. dom. Node;
Import org. w3c. dom. NodeList;
 
// Obtain the node value of the corresponding node name of the specified Node
Public String getNodeValue (Node parentNode, String nodeName ){
String s = "";
If (parentNode. getNodeType () = Node. ELEMENT_NODE ){
 
Element rootElement = (Element) parentNode;
 
NodeList childList = rootElement. getElementsByTagName (nodeName );
Element childElement = (Element) childList. item (0 );
If (childElement! = Null ){
NodeList textFNList = childElement. getChildNodes ();
If (textFNList! = Null ){
Node temp = (Node) textFNList. item (0 );
If (temp! = Null ){
S = temp. getNodeValue ();
If (s! = Null)
S = s. trim ();
}
}
}
}
Return s;
}
 
// Obtain the subnode of the specified Node
Public NodeList getNodeList (Node node ){
NodeList nodeList = node. getChildNodes ();
Return nodeList;
}
// Obtain the node with the specified node name
Public Node getNodeByTagName (Node parentNode, String tagName ){
Element rootElement = (Element) parentNode;
NodeList nodeList = rootElement. getElementsByTagName (tagName );
If (nodeList. getLength ()> 0)
Return nodeList. item (0 );
Else
Return null;
}
 
// Obtain the node list of the specified node name
Public NodeList getNodeListByTagName (Node parentNode, String tagName ){
Element rootElement = (Element) parentNode;
NodeList nodeList = rootElement. getElementsByTagName (tagName );
Return nodeList;
}
 
// Obtain the specified property value
Public String getNodeAttribute (Node node, String attName ){
Element elem = (Element) node;
Return elem. getAttribute (attName );
}
 
// Create a node and set attributes
Public Node createNode (String tagName, Map <String, String> attributeMap ){
Element element = doc. createElement (tagName );
If (attributeMap! = Null &&! AttributeMap. isEmpty ()){
Iterator <Entry <String, String> it = attributeMap. entrySet ()
. Iterator ();
While (it. hasNext ()){
Entry <String, String> entry = it. next ();
Element. setAttribute (entry. getKey (), entry. getValue ());
}
}
Return element;
}
This article briefly introduces the packages and classes for operating xml in java se, and provides methods for parsing and converting inputstream and operating node and node attributes, we demonstrated how to operate xml in a simple way in the future, not only relying on third-party toolkit.

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.