龙空技术网

java程序中xml格式对象与xml字符串互转

木容小复 43

前言:

目前小伙伴们对“dom4j对象转xml字符串”都比较关切,各位老铁们都需要知道一些“dom4j对象转xml字符串”的相关文章。那么小编在网上收集了一些对于“dom4j对象转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 = "<root><hello>helloContent1</hello></root>";        // 解析xml字符串获取Document对象        Document documentDe = DocumentHelper.parseText(xmlStrs);        Element rootElement = documentDe.getRootElement();        // 1 获取根节点下元素 2 其节点内容        Element eleHello = rootElement.element("hello");        System.out.println("节点内容:" + eleHello.getText());        List<Element> elementList = rootElement.elements(); // 根下元素集合        String convertXml = documentDe.asXML();        System.out.println("格式xml对象转换xml字符串:" + 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("F:\\xbl\\x1.xml"));        Element rootEle = document.getRootElement();        Element helloEle = rootEle.element("hello");        System.out.println("这是从xml文件获取xml节点字符串:" + helloEle.getText());    }	public static void main(String[] args) throws Exception {		// 测试代码        new Helloworld().xmlFromFile();	}}

测试xml文件:x1.xml

标签: #dom4j对象转xml字符串