> 教育
javaxml对象(java对xml有哪些解析技术)
导语:java程序中xml格式对象与xml字符串互转
(1) java程序中xml格式对象与xml字符串互转
import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;public class Helloworld { private void xmlDocument() throws Exception { String xmlStrs = &34;; // 解析xml字符串获取Document对象 Document documentDe = DocumentHelper.parseText(xmlStrs); Element rootElement = documentDe.getRootElement(); // 1 获取根节点下元素 2 其节点内容 Element eleHello = rootElement.element(&34;); System.out.println(&34; + eleHello.getText()); List<Element> elementList = rootElement.elements(); // 根下元素集合 String convertXml = documentDe.asXML(); System.out.println(&34; + convertXml); }public static void main(String[] args) throws Exception {// 测试代码 new Helloworld().xmlDocument();}}
(2) java程序中从xml文件获取节点字符串
import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class Helloworld {private void xmlFromFile() throws Exception { SAXReader saxReader = new SAXReader(); Document document = saxReader.read(new File(&34;)); Element rootEle = document.getRootElement(); Element helloEle = rootEle.element(&34;); System.out.println(&34; + helloEle.getText()); }public static void main(String[] args) throws Exception {// 测试代码 new Helloworld().xmlFromFile();}}
测试xml文件:x1.xml
本文内容由小面整理编辑!