日期:2014-05-20 浏览次数:20863 次
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<resource name="level1" >
<resource name="level2" >
<resource name="level3" >
</resource>
</resource>
</resource>
<resource name="text1" >
</resources>
public class Xml2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub 10jq
Node root=new Node();
root.text="";
root.children=new ArrayList<Node>();
Node level1=new Node();
level1.text="level1";
level1.children=new ArrayList<Node>();
Node level2=new Node();
level2.text="level2";
level2.children=new ArrayList<Node>();
Node level3=new Node();
level3.text="level3";
level3.children=new ArrayList<Node>();
level2.children.add(level3);
level1.children.add(level2);
Node text1=new Node();
text1.text="level3";
text1.children=new ArrayList<Node>();
root.children.add(text1);
}
}
class Node{
public String text;
public List children;
}
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.sun.org.apache.regexp.internal.recompile;
import com.yxd.pris.model.TVideo;
/**
*功能说明:
*
*创建人: 刘飞
*
*创建时间:2014-1-27 下午04:58:49
*
*修改人 修改时间 修改描述
*
*
*Copyright (c)2014
*
*/
public class Node {
private String text;
private List children;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
}
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<resources>" +
"<resource name=\"level1\" >" +
"<resource name=\"level2\" >" +
" <resource name=\"level3\" >" +
"</resource>" +
"</resource>" +
"</resource>" +
"<resource name=\"text1\" />" +
"</resources>";
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
Element rootElt = doc.getRootElement(); // 获取根节点
Node node = new Node();
node.setText(rootElt.attributeValue("name"));
node.recursiveXML(rootElt, 0, node);
} catch (DocumentException e) {
e.printStackTrace();
} // 将字符串转为XML
}
private void recursiveXML(Element element,int next,Node node) {
node.children = new ArrayList<Node>();
String url ="/";
for (int i = 0; i < next; i++) {
url = url+"/resource";
}
next++;
List list = element.selectNodes(url);
if (list.size() > 0 ) {
Iterator resource = element.elementIterator("resource"); //获取根节点下的子节点resource
//遍历zone节点
while (resource.hasNext()) {
Element resourceEle = (Element) resource.next();
String resourceName = resourceEle.attributeValue("name");
Node childNode = new Node();
childNode.setText(resourceName);
node.children.add(childNode);
recursiveXML(resourceEle,next,childNode);