读写xml笔记

前端之家收集整理的这篇文章主要介绍了读写xml笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

读写xml

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class TestReadXml {

public static String getClassPath() {
return XmlParser. class .getClass().getResource( "/" ).toString();
}

public static void ff() {
File f2 = new File(XmlParser. class .getResource( "" ).getPath());
System. out .println(f2);
}

public static void main(String[] args) {
try {
SAXReader reader = new SAXReader();
String xmlPath = System.getProperty( "user.dir" ) + "\\src\\test\\java\\test.xml" ;
File file = new File(xmlPath);
if (file.exists()) {
Document document = reader.read(file);
Element root = document.getRootElement();
// 根据节点名获取节点
System. out .println(root.element( "login" ).getTextTrim());

// 遍历节点
for (Iteratori = root.elementIterator(); i.hasNext();) {
Element element = (Element) i.next();
System. out .println(element.asXML());
}

// 根据xpath根据节点名,节点属性查找指定的节点
System. out .println( "----------------------获取指定节点的值----------------------------------" );
List<Node> node1 =root.selectNodes( "//p[@id='hehe']" );
for (Node n : node1) {
System. out .println(n.getName());
System. out .println(n.getText());
}
System. out .println( "----------------------精确查找----------------------------------" );
// 精确查找
List<Node> node2 =root.selectNodes( "//div/p[@id='hi']" );
for (Node n : node2) {
System. out .println(n.getName());
System. out .println(n.getText());
}
//hhxml节点名
Element hh = root.element( "hh" );

System. out .println( "---------------------获取父节点的名字-----------------------" );
// 获取父节点
System. out .println(hh.getParent().getName());

// 设置节点的值
hh.setText( "21" );
System. out .println(hh.getText());

// 写入文件
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding( "utf-8" );
XMLWriter writer = new XMLWriter( new FileWriter(xmlPath),format);
writer.write(document);
writer.close();

/*
* //获取子节点 System.out.println(hh.getNodeType());
* System.out.println(hh.getData());
* System.out.println(hh.getName());
* System.out.println(hh.getText());
* System.out.println(hh.getTextTrim()); hh.setText("21");
* System.out.println(hh.getTextTrim());
*/
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}
//参考网址:http://berdy.iteye.com/blog/807883
//
原文链接:https://www.f2er.com/xml/296694.html

猜你在找的XML相关文章