dom4j parsing xml string

Use dom4j to parse the xml string into a map:

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

@SuppressWarnings("unchecked")
public class XmlParser {
	public static Map<String,Object> readData(Element ele){
    	Map<String,Object> map = new HashMap<String,Object>();
    	//get element list traversal
		List <Element> eList = ele.elements ();
        for (Element e: eList) {
        	if(e.elements().isEmpty()){
        		//If the element child element is empty, get the text directly
        		// e.getData() e.getStringValue();e.getText()e.getTextTrim()
        		map.put(e.getName(), e.getText());
        	}else{
        		//If there are child elements, recursively retrieve the value
        		map.put(e.getName(), readData(e));
        	}
        }
    	return map;
    }
	public static Map<String,Object> readXml(String xml){
    	Map<String,Object> map = null;
    	try{
    		Document doc = DocumentHelper.parseText(xml);
        	// get the root node
            Element rootElt = doc.getRootElement();
            // get data from root node
            map = readData(rootElt);
    	}catch(Exception e){
    		e.printStackTrace ();
    	}
    	return map;
    }
	public static void main(String[] args) {
		 String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><a><c> 6  6 </c></a><b>2</b></root>";
    	 Map<String,Object> root = readXml(str);
    	 for (Map.Entry<String, Object> entry : root.entrySet()) {  
    		 System.out.println(entry.getKey() + ":" + entry.getValue());  
    	 }
	}
}

 Remark:

1) The element name is used as the key in the code. If you need to use some attribute value as the key, you can use the attributeValue method to get the name as the key.

2) There are four methods to get the node value: e.getData() e.getStringValue() e.getText() e.getTextTrim()

The difference between getText and getTextTrim can be understood by looking at the names. getTextTrim is to remove the left and right spaces (if there are two or more spaces in the content, it will be converted to one space); getStringValue is to take all the strings under the node , if there is a subtag, the text in the subtag will be spelled into a string and returned. To put it bluntly, it is the splicing of the content after removing all the element tags under the element; for getData, after testing, the result is consistent with getText.

3) Using reflection can convert map to Javabean object (code too lazy to write =_=).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326994045&siteId=291194637