论坛首页 入门技术论坛

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

浏览 1430 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-03  

 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();
  }
 }

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics