import java.io.StringReader; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class TestA { public static String test(){ Document document = DocumentHelper.createDocument(); Element element = document.addElement("aaaa"); Element ele1 = element.addElement("bbbb"); Element ele2 = element.addElement("cccc"); ele1.addText("1"); ele2.addText("你好"); return document.asXML(); } public static void main(String[] args) { String test = test(); System.out.println(test); StringReader stringReader = new StringReader(test); SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(stringReader); } catch (DocumentException e) { e.printStackTrace(); } Element element = doc.getRootElement(); String resultCode = element.elementText("bbbb"); String resultMsg = element.elementText("cccc"); System.err.println("[aaaa]" + resultCode); System.err.println("[bbbb]" + resultMsg); } }
结果:
<?xml version="1.0" encoding="UTF-8"?> <aaaa><bbbb>1</bbbb><cccc>你好</cccc></aaaa> [aaaa]1 [bbbb]你好
时间: 2024-11-06 03:49:31