maven项目使用dom4j处理xml文件的解析与创建

获取文件路径方法:

 获取的文件默认在target目录下的classes中。

String fileName = 类名.class.getClassLoader().getResource("文件名").getPath();

 使用的xml文档内容:

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book author="天蚕土豆">
        <name>斗破苍穹</name>
        <price>86</price>
    </book>
    <book author="萧潜">
        <name>缥缈之旅</name>
        <price>92</price>
    </book>
    <book author="萧鼎">
        <name>诛仙</name>
        <price>98</price>
    </book>
    <book author="天下霸唱">
        <name>鬼吹灯</name>
        <price>124</price>
    </book>
    <book author="辰东">
        <name>神墓</name>
        <price>128</price>
    </book>
</books>

配置maven环境:

 在pom文件中加入以下代码

	<dependency>
	    <groupId>dom4j</groupId>
	    <artifactId>dom4j</artifactId>
	    <version>1.6.1</version>
	</dependency>

(也可以自己去maven中找想要的版本)

 

读取xml文档转为dom4j的document对象:(解析xml使用)

/**
	 * 读取xml文件转为document对象
	 * @param file
	 * @return
	 * @throws DocumentException
	 */
	public static Document parse(File file) throws DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(file);
		return document;
	}

解析xml:(返回对象为List<Element>,为了方便创建文档使用)

解析xml文件代码:

	/**
	 * 解析xml文档
	 * @param file
	 * @throws DocumentException 
	 */
	public static List<Element> resolve(File file) throws DocumentException {

			Document document = parse(file);
			//获取根元素
			Element rootElement = document.getRootElement();
			//获取根元素的对象
			List<Element> elements = rootElement.elements();
			//将根元素的对象的值拿出来
			for(Element book : elements) {
				String author = book.attributeValue("author");
				String name = book.element("name").getText();
				String price = book.element("price").getText();
				System.out.println(name+" "+author+" "+price);
			}
			return elements;
	}

创建xml文档并写入文件:

创建xml文档代码:

/**
	 * 创建xml文档
	 * @return
	 */
	public static Document createDocument(List<Element> list) {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("root");
		
		for(Element book : list) {
			String author = book.attributeValue("author");
			String name = book.element("name").getText();
			String price = book.element("price").getText();
			root.addElement("book").addAttribute("name", name).addAttribute("price", price).addAttribute("author", author);
		}
		
		return document;
	}

写入文件中:

/**
	 * 将创建的xml文档写入文件中
	 * @param document
	 * @throws IOException
	 */
	public static void write(Document document) throws IOException {

		XMLWriter writer = new XMLWriter(
			new FileWriter( "路径+文件名" )
		);
		writer.write( document );
		writer.close();

	}

最后附上dom4j的github使用指南,有需要别的功能的童鞋可以前往学习。

dom4j使用指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值