关于dom4j使用说明,创建xml文件和解析xml文件或字符串-2
dom4j解析xml 字符串
创建一个Document 对象
Document doc = null;
读取并解析XML文档 }
SAXReader就是一个管道,用一个流的方式,把xml文件读出来 }
获取文件 解析文件xml
SAXReader reader = new SAXReader(); }
Document document = reader.read(new File("User.hbm.xml")); }
将字符串 转为xml
doc = DocumentHelper.parseText(xml); // 将字符串转为XML
获取根节点
Element rootElt = doc.getRootElement();
输出根节点的名称
System.out.println("根节点:" + rootElt.getName());
获取根节点下的head节点
Iterator iter = rootElt.elementIterator("head");
遍历head节点
while (iter.hasNext()) {
Element recordEle = (Element) iter.next();
String title = recordEle.elementTextTrim
("title"); // 拿到head节点下的子节点title值
System.out.println("title:" + title);
Iterator iters =
recordEle.elementIterator("script"); // 获取子节点head下的子节点script
// 遍历Header节点下的Response节点
while (iters.hasNext()) {
Element itemEle = (Element)
iters.next();
String username =
itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点
username的值
String password =
itemEle.elementTextTrim("password");
System.out.println("username:" +
username);
System.out.println("password:" +
password);
}
}
main 方法
public static void main(String[] args) {
String Stringxml = "<ROOT>"
+ "<head>"
+ "<title>dom4j解析一个例子2</title>"
+ "<script>"
+ "<username>yangrong</username>"
+ "<password>123456</password>"
+ "</script>"
+ "</head>"
+ "</ROOT>";
RXML xml = new RXML();
xml.AnalysisXML(Stringxml);}