读取指定路径下的xml文件,以json格式输出
![Alt](https://i-blog.csdnimg.cn/blog_migrate/2c5626d1121945cb84be5bc1cdd2de45.gif)
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class parseXml
{
public static void main(String[] args)
{
File file = new File("F:\\template\\LIVE_H264_480P_BGM_FILTER.xml");
SAXReader reader = new SAXReader();
Document document = null;
try
{
document = reader.read(file);
}
catch (DocumentException e)
{
e.printStackTrace();
}
Element rootEle = document.getRootElement();
System.out.println("根节点:" + rootEle.getName());
Iterator param = rootEle.elementIterator("param");
List<Template> templateList = new ArrayList<>();
while (param.hasNext())
{
Element element = (Element)param.next();
String name = element.attributeValue("name");
String value ="";
Attribute attribute ;
if (element.attribute("value") != null){
attribute = element.attribute("value");
value = attribute.getValue();
}
Template template = new Template();
template.setName(name);
template.setValue(value);
templateList.add(template);
System.out.println("name:" + name + " value:" + value );
}
System.out.println(templateList);
String template =JSON.toJSON(templateList).toString();
System.out.println(template);
}
}