【Springboot】springboot中处理xml格式文件的依赖

对xml文件的解析可以使用下述的依赖:

		<!-- 解析xml文件 -->
		<dependency>
			<groupId>org.dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>2.1.3</version>
		</dependency>

项目目录结构如下:
在这里插入图片描述
NewFile.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!--学生信息表-->
<Students>
	<Student>
		<Name class="name">张三</Name>
		<Age>17</Age>
		<Sex></Sex>
	</Student>
	<Student>
		<Name class="name1">李四</Name>
		<Age>20</Age>
		<Sex></Sex>
	</Student>
</Students>

解析代码:

public class XmlController {
	public static void main(String[] args) throws DocumentException {
		getXmlDocument();
	}

	public static void getXmlDocument() throws DocumentException {
		String path=XmlController.class.getClassLoader().getResource("NewFile.xml").getFile();
		System.out.println(path);
		File file=new File(path);
		SAXReader saxReader=new SAXReader();
		Document document=saxReader.read(file);
		Element root=document.getRootElement();
		List<Element> elements=root.elements();
		for (Element element : elements) {
			for (Element node : element.elements()) {
				System.out.println(node.getText());
			}
		}
	}
	
}

输出结果:

张三
17
男
李四
20
男
原创文章 79 获赞 7 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qgnczmnmn/article/details/106072953
今日推荐