Read and write xml using dom4j
Advertisements
Java code
- public class XMLUtils (
- / **
- * Generated xml file
- * @ Param doc
- * @ Param fileName
- * @ Param encoding
- * /
- public static void createXMLFile (Document doc, String fileName, String encoding) (
- XMLWriter writer = null;
- try (
- if (StringUtils.isNotEmpty (encoding)) (
- OutputFormat format = OutputFormat.createPrettyPrint ();
- format.setEncoding (encoding); / / specify the XML encoding
- writer = new XMLWriter (new FileWriter (fileName), format);
- ) Else (
- writer = new XMLWriter (new FileWriter (fileName));
- )
- writer.write (doc);
- ) Catch (IOException e) (
- e.printStackTrace ();
- ) Finally (
- try (
- writer.close ();
- ) Catch (IOException e) (
- e.printStackTrace ();
- )
- )
- )
- / **
- * Create Document and returns root node
- * @ Param root_label root tag
- * @ Return
- * /
- public static Document createDocument (String root_label) (
- Document doc = DocumentHelper.createDocument ();
- doc.setRootElement (doc.addElement (root_label));
- return doc;
- )
- / **
- * A string into XML
- * @ Param xml_string
- * @ Return
- * /
- public static Document createDocumentFromXmlString (String xml_string) (
- if (StringUtils.isEmpty (xml_string)) (
- xml_string = "<students> <class> test </ class> </ students>";
- )
- Document document = null;
- try (
- document = DocumentHelper.parseText (xml_string);
- ) Catch (DocumentException e) (
- e.printStackTrace ();
- )
- return document;
- )
- / **
- * To add sub-nodes node
- * @ Param root the relative root
- * @ Param newNode the new node
- * @ Param nodeId node Id
- * @ Param elements node element
- * /
- public static void addNodeElement (Element root, String newNode, String nodeId, Map elements) (
- Element _newNode = root.addElement (newNode);
- _newNode.addAttribute ("id", nodeId). addAttribute ("no", nodeId); / / Set properties
- Iterator it = elements.entrySet (). Iterator ();
- while (it.hasNext ()){// node elements and values under the
- Map.Entry entry = (Map.Entry) it.next ();
- Object key = entry.getKey ();
- Object value = entry.getValue ();
- _newNode.addElement ((String) key). setText ((String) value);
- )
- )
- / **
- * XML document or node into a string
- * @ Param filePath
- * @ Return
- * /
- public static String readXMLAsString (String filePath) (
- SAXReader reader = new SAXReader ();
- Document document = null;
- try (
- document = reader.read (new File (filePath));
- / / Element root = document.getRootElement ();
- ) Catch (DocumentException e) (
- e.printStackTrace ();
- )
- return document.asXML ();
- )
- / **
- * Print all the child nodes node
- * @ Param element
- * /
- publicstatic void printAllChildNode (Element element) (
- / / Loop current node attributes
- Iterator attrs = element.attributeIterator ();
- while (attrs.hasNext ()) (
- Attribute attr = (Attribute) attrs.next ();
- System.out.println (attr.getName () + "=" + attr.getText ());
- )
- / / Loop the child element nodes
- Iterator elements = element.elementIterator ();
- while (elements.hasNext ()) (
- Element ele = (Element) elements.next ();
- if (ele.attribute ("id") == null) (
- System.out.println (ele.getName () + "=" + ele.getText ());
- )
- / / Recursive call
- printAllChildNode (ele);
- )
- )
- / ***
- * To read data xpath
- * @ Param filePath
- * @ Param xpath
- * /
- public static void printElementsByXPath (String filePath, String xpath) (
- SAXReader reader = new SAXReader ();
- try (
- Document doc = reader.read (new File (filePath));
- List properties = doc.selectNodes (xpath);
- Iterator it = properties.iterator ();
- while (it.hasNext ()) (
- Element elm = (Element) it.next ();
- System.out.println (elm.getText ());
- )
- )
- catch (Exception ex) (
- ex.printStackTrace ();
- )
- )
- public static void main (String [] args) (
- Map <String,String> elements = new HashMap <String,String> ();
- elements.put ("name", "Joe Smith");
- elements.put ("sex", "M");
- elements.put ("age", "20");
- Document doc = XMLUtils.createDocumentFromXmlString ("<students> </ students>");
- doc.getRootElement (). addAttribute ("year", "2000");
- XMLUtils.addNodeElement (doc.getRootElement (), "student", "20090313001", elements);
- elements.clear ();
- elements.put ("name", "John Doe");
- elements.put ("sex", "M");
- elements.put ("age", "21");
- XMLUtils.addNodeElement (doc.getRootElement (), "student", "20090313002", elements);
- String filePath = "D: / test.xml";
- XMLUtils.createXMLFile (doc, filePath, "GBK");
- / / System.out.println (XMLUtils.readXMLAsString (filePath));
- XMLUtils.printElementsByXPath (filePath, "/ students / student [@ id = \" 20090313001 \ "] / name");
- XMLUtils.printAllChildNode (doc.getRootElement ());
- )
- )
public class XMLUtils {
/**
* Generates an XML file
* @param doc
* @param fileName
* @param encoding
*/
public static void createXMLFile(Document doc,String fileName,String encoding){
XMLWriter writer = null;
try{
if(StringUtils.isNotEmpty(encoding)){
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(encoding); // The specified XML encoding
writer = new XMLWriter(new FileWriter(fileName),format);
}else{
writer = new XMLWriter(new FileWriter(fileName));
}
writer.write(doc);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
/**
* Create a Document and returns the root node
* @param root_label The root tag
* @return
*/
public static Document createDocument(String root_label){
Document doc = DocumentHelper.createDocument();
doc.setRootElement(doc.addElement(root_label));
return doc;
}
/**
* Converts a string into XML
* @param xml_string
* @return
*/
public static Document createDocumentFromXmlString(String xml_string){
if(StringUtils.isEmpty(xml_string)){
xml_string = "<students> <class>test</class> </students>";
}
Document document = null;
try {
document = DocumentHelper.parseText(xml_string);
} catch (DocumentException e) {
e.printStackTrace();
}
return document;
}
/**
* To add the child nodes of node
* @param root Relative root
* @param newNode The new nexus
* @param nodeId Nexus Id
* @param elements Node elements
*/
public static void addNodeElement(Element root,String newNode,String nodeId,Map elements){
Element _newNode = root.addElement(newNode);
_newNode.addAttribute("id", nodeId).addAttribute("no", nodeId);// Setting properties
Iterator it = elements.entrySet().iterator();
while(it.hasNext()){// Nexus of elements and values
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
_newNode.addElement((String)key).setText((String)value);
}
}
/**
* Add a document or an XML node into a string
* @param filePath
* @return
*/
public static String readXMLAsString(String filePath){
SAXReader reader = new SAXReader();
Document document=null;
try {
document = reader.read(new File(filePath));
//Element root=document.getRootElement();
} catch (DocumentException e) {
e.printStackTrace();
}
return document.asXML();
}
/**
* Print all the child nodes of the node
* @param element
*/
public static void printAllChildNode(Element element){
// Loop current node properties
Iterator attrs = element.attributeIterator();
while(attrs.hasNext()){
Attribute attr = (Attribute)attrs.next();
System.out.println(attr.getName() + "=" + attr.getText());
}
// Loop the child element node
Iterator elements = element.elementIterator();
while(elements.hasNext()){
Element ele = (Element)elements.next();
if(ele.attribute("id") == null){
System.out.println(ele.getName() + "=" + ele.getText());
}
// Recursive calls
printAllChildNode(ele);
}
}
/***
* In XPath read data
* @param filePath
* @param xpath
*/
public static void printElementsByXPath(String filePath,String xpath){
SAXReader reader = new SAXReader();
try{
Document doc = reader.read(new File(filePath));
List properties=doc.selectNodes(xpath);
Iterator it=properties.iterator();
while(it.hasNext()){
Element elm=(Element)it.next();
System.out.println(elm.getText());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args){
Map<String,String> elements = new HashMap<String,String>();
elements.put("name", " Smith, John ");
elements.put("sex", " Male ");
elements.put("age", "20");
Document doc = XMLUtils.createDocumentFromXmlString("<students></students>");
doc.getRootElement().addAttribute("year", "2000");
XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313001", elements);
elements.clear();
elements.put("name", " Paul Lee ");
elements.put("sex", " Male ");
elements.put("age", "21");
XMLUtils.addNodeElement(doc.getRootElement(), "student", "20090313002", elements);
String filePath = "D:/test.xml";
XMLUtils.createXMLFile(doc, filePath, "GBK");
//System.out.println(XMLUtils.readXMLAsString(filePath));
XMLUtils.printElementsByXPath(filePath, "/students/student[@id=\"20090313001\"]/name");
XMLUtils.printAllChildNode(doc.getRootElement());
}
}
Second, the use XPATH
Xml Code
- <AAA>
- <BBB/>
- <CCC/>
- <BBB/>
- <BBB/>
- <DDD>
- <BBB/>
- </ DDD>
- <CCC/>
- </ AAA>
<AAA>
<BBB/>
<CCC/>
<BBB/>
<BBB/>
<DDD>
<BBB/>
</DDD>
<CCC/>
</AAA>
(1) If it is a slash "/" start, which is described in the request element's absolute path.
Example structure:
- Access element "AAA "----" / AAA ".
- Access element "CCC" --- "/ AAA / CCC", visit the following sub-root node AAA CCC, the regular collection by the two nodes.
- Visit the root node AAA DDD sub-sub-node BBB: "/ AAA / DDD / BBB".
(2) If the path expression to "/ /" start, it will find all the elements of compliance rules <br /> example structure:
- "/ / BBB", select all the elements of <BBB/>, in this case a total of four
- "/ / DDD / BBB", select the element node "DDD" child node under the "BBB", only to meet the elements of "BBB" to "DDD" sub-element will be selected, in this case 1.
(3) "*" in front of the path chosen by the positioning of all elements of <br /> Example:
- "/ AAA / *" said the root of all the elements of choice
- "/ * / CCC" Select a parent element of the "CCC" element ,"/*/*/ BBB "select the third class under the root of all the" BBB "element
- "//*" That match all of the elements
(4) the expression in square brackets can be further specified element number in square brackets, said the location of the selected elements of the collection, last () function that sets the selected element the last element
- "/ AAA / BBB [2]" said Root "BBB" A collection of elements of the second element
- "/ AAA / BBB [last ()]" said Root "BBB" the last element of the collection element
(5) "@" means property
Xml Code
- <AAA>
- <BBB Id = "b1" />
- <BBB Id = "b2" />
- <BBB Name = "bbb" />
- <BBB/>
- </ AAA>
<AAA>
<BBB id = "b1"/>
<BBB id = "b2"/>
<BBB name = "bbb"/>
<BBB/>
</AAA>
- "/ / @ Id" mean that all named "id" attribute
- "/ / BBB [@ id]" that all elements with ID attributes of the BBB
- "/ / BBB [@*]" said the BBB with all elements of property, in this case <BBB/> will not be selected, the other three were selected
- "/ / BBB [not (@*)]" that the element has no attributes, in this case <BBB/> is selected, the other three elements are not selected
(6) The value of the property can be used as selection criteria, the function "normalize-space" can be removed to the head and tail of the space, or replaced with a single space
Xml Code
- <AAA>
- <BBB Id = "b1" />
- <BBB Name = "bbb" />
- <BBB Name = "bbb" />
- </ AAA>
<AAA>
<BBB id = "b1"/>
<BBB name = " bbb "/>
<BBB name = "bbb"/>
</AAA>
- "/ / BBB [@ id = 'b1']": select the attribute value "b1" elements "BBB"
- "/ / BBB [@ name = 'bbb']": select the attribute value of "bbb" of the elements, attention to a property called name as each element of "BBB", its value has spaces, will not be selected.
- "/ / BBB [normalize-space (@ name) = 'bbb']": select the name "name", and its value "bbb", the value can have spaces before and after, this example will select two "BBB "Elements
(7) function count (*): calculate the number of selected elements
- "//*[ Count (BBB) = 2] ", selected with the two" BBB "sub-elements of elements
- "//*[ Count (*) = 2] ", select the element contains two child elements
Related Posts of Read and write xml using dom4j
-
Build flex + spring + blazeds + hibernate application
Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...
-
JAVA EE JSP_JNDI
dsfdsa http://lindows.javaeye.com/admin/blogs/213348 Tomcat 6 with the connection pool data source configuration http://www.blogjava.net/ec2008/archive/2008/07/19/216063.html project: test Driver path: D: \ workspace \ test \ WebRoot \ WEB-INF \ lib ...
-
Hibernate connection pool configuration
Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15
-
hibernate generic generic DAO
package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *
-
First Hibernate Example
Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co
-
Struts2 + hibernate + spring problem user log in
dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q
-
Hibernate secondary cache
Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...
-
The level Hibernate cache
Hibernate cache level: (1) a cache is very short and the session life cycle consistent, also known as session-level cache-level cache or transaction-level cache (2) Ways of Supporting level cache: get (); load (); iterator (); only entity object cach ...
-
Hibernate's lazy strategy
hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...












