使用Jdom来把一棵完整的树生成XML

 public String parseXML() {
  String parseContent = JspUtils.getParameter(getRequest(),
    "parseContent", "");
  Long deep = JspUtils.getLongParameter(getRequest(), "deep", new Long(-1));
  String selectInfos = JspUtils.getParameter(getRequest(), "selectInfos",
    "");
  List categorys = categoryManageService.findSubCategories(null, null,
    false, parseContent, true);

  Element root = new Element("root");
  root.setAttribute("type", selectInfos);

  Element curElement = root;

  if (!Utilities.isNullOrEmpty(categorys)) {
   for (int i = 0; i < categorys.size(); i++) {
    Category c = (Category) categorys.get(i);
    Element elements = new Element("node");
    elements.setAttribute("type", "category");
    elements.setAttribute("tId", c.getId() + "");
    elements.setAttribute("pId",
      c != null && c.getParent() != null ? c.getParent()
        .getId()
        + "" : "-1");
    elements.setAttribute("name", c != null
      && !StringUtils.isNullOrEmpty(c.getName()) ? c
      .getName() : "");
    if (selectInfos.equalsIgnoreCase("topic")) {
     Element tElement = null;
     List<Topic> topics = categoryManageService.findTopics(c);
     if (!Utilities.isNullOrEmpty(topics)) {
                for (Topic topic : topics) {
                 tElement = new Element("node");
                 tElement.setAttribute("tId", topic != null ? topic.getId()+"" : "01");
                 tElement.setAttribute("pId", c.getId() + "");
                 tElement.setAttribute("name", topic != null && !StringUtils.isNullOrEmpty(topic.getName()) ? topic.getName() : "");
              elements.addContent(tElement);
                }
     }
    }
    addElementIntoEML(elements, curElement, root);
    System.out.println(curElement);
   }
  }
  
  Document doc = new Document(root);
  String newFile = "E:/xml/"+selectInfos+".xml";
  try {
   File file = new File(newFile);
   if (!file.exists()) {
    file.createNewFile();
   }
   XMLOutputter XMLOut = new XMLOutputter();
   OutputStream os = new FileOutputStream(file);
   XMLOut.setEncoding("utf-8");
   XMLOut.setNewlines(true);
   XMLOut.setIndent(3);
   
   XMLOut.output(doc, os);
   os.close();
  } catch (Exception e) {
   e.printStackTrace();
  } 
  getRequest().setAttribute("newFile", newFile);
  return "parseXML";
 }

 

 private void addElementIntoEML(Element newElement, Element curElement, Element root) {
  Element temp = curElement;
  while (temp != null) {
   if (newElement.getAttributeValue("pId").equals(temp.getAttributeValue("tId"))
     || temp.getAttributeValue("type").equals(root.getAttributeValue("type"))) {
    temp.addContent(newElement);
    curElement = newElement;
    return;
   }
   temp = temp.getParent();
  }
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值