Use dom4j to parse xml files or xml strings

tags: dom4j  Xml parsing  Xml file  Xml string

There is a configuration file that needs to parse out the root node and child nodes, as well as the information of the attributes under the child nodes. Although the w3c.dom specification can be parsed, we try to parse it using dom4j.

The jar package involved has dom4j-1.6.1.jar

 

Xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="computer" class="org.crazyit.app.main.Computer">
		 <property name="name" value="SUN Wukong's smart phone" />
		<property name="out" ref="betterPrinter" />
	</bean>
	
	<bean id="printer" class="org.crazyit.app.inter.impl.Printer" />
	<bean id="betterPrinter" class="org.crazyit.app.inter.impl.BetterPrinter" />
	
	<bean id="now" class="java.util.Date" scope="prototype" />
</beans>

 

Parse the java class of the xml configuration file:

SAXReader reader = new SAXReader();
Document doc = reader.read(new File(filePath));
 / / Get the root node
Element root = doc.getRootElement();

 / / Traverse the child nodes under the root node (also can traverse a child node with child nodes)
for(Object obj : root.elements()) {
    Element ele = (Element) obj;
 / / Get the properties of the child node
    String beanId = ele.attributeValue("id");
    String beanClazz = ele.attributeValue("class");
    String beanScope = ele.attributeValue("scope");
}

 

Parse the string in xml format:

Map map = new HashMap();
 StringReader reader = new StringReader(msg);
 InputSource source = new InputSource(reader);
 SAXReader sr = new SAXReader();

 Document doc = sr.read(source);

 / / After getting the Document, the following steps are consistent with the steps above to parse the xml file

 

But if it is a general type: such as html configuration file (that is, not this Spring xml), the parsing syntax is different, such as:

 

 Map map = new HashMap();  
        Document doc = null;  
        try {  
            Doc = DocumentHelper.parseText(xml); // Convert string to XML  
  
                         Element rootElt = doc.getRootElement(); // Get the root node  
  
                         System.out.println("root node:" + rootElt.getName()); // get the name of the root node  
  
  
                         Iterator iter = rootElt.elementIterator("head"); // Get the child node head under the root node  
  
                         // traverse the head node  
  
            while (iter.hasNext()) {  
  
                Element recordEle = (Element) iter.next();  
                                 String title = recordEle.elementTextTrim("title"); // Get the child node title value under the head node  
  
                System.out.println("title:" + title);  
                map.put("title", title);  
  
                                 Iterator iters = recordEle.elementIterator("script"); // Get the child node script under the child node head  
  
  
                                 // Traverse the Response node under the Header node (continue to traverse if there are child nodes under the child node)  
  
               
        
  
                         Iterator iterss = rootElt.elementIterator("body"); ///Get the child node under the root node  
  
                         / / Traverse the body node  
  
            while (iterss.hasNext()) {  
                Element recordEless = (Element) iterss.next();  
                                 String result = recordEless.elementTextTrim("result"); // Get the child node result value under the body node  
  
                System.out.println("result:" + result);  
  
                                 Iterator itersElIterator = recordEless.elementIterator("form"); // Get the child nodes from the child body from 
  
                                 / / Traverse the from node under the body node  
  
               
            }  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return map;  
    }  
  
 

 

 

Intelligent Recommendation

Use dom4j to parse xml document

note: When using dom4j to parse the xml document, first we need to import the dom4j jar packagedom4j-1.6.1.jar Reference link: https://www.jianshu.com/p/e8561ea99d03 One. In dom4j, there are three way...

Use Dom4j to parse XML documents

Use Dom4j to parse XML documents What is Dmo4j? ​ dom4j is a Java XML API, an upgrade of jdom, used to read and write XML files, dom4j is a very goodJavaXML API has the characteristics of excellent pe...

Use dom4j to parse XML into JSON

The jar packages are: dom4j-1.6.1.jar and fastjson-1.2.31.jar The maven dependency is: Example...

Use dom4j to parse xml in java

Don’t say much, just go straight xml document: Example 1: Use List to parse xml Example 2: Use Iterator to parse xml result:   Example 3: Create xml document and output to file result: &nbs...

More Recommendation

Dom4j parses xml files and strings

Parse the xml string as follows     Parse the xml file, the xml file is as follows   The parsed code is as follows    ...

Use Dom4j to parse custom database XML configuration files

Why use XML to configure database information When we are writing a small Demo, we will configure the connection information of the database every time. Even if we write a connection tool class by our...

Simply use DOM4J to parse XML (how to use dom4j to read xml)

First, download a DOM4J jar package, choose one of the following two websites, and import the project after downloading http://mvnrepository.com/artifact/dom4j/dom4j/1.6.1 www.dom4j.org The realizatio...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top