【问题标题】:Add and Remove Elements from XML - DOM Parser - Java从 XML 添加和删除元素 - DOM 解析器 - Java
【发布时间】:2015-06-12 20:52:50
【问题描述】:

XML

<company> <employee>
<age> 12 </age>
  <name> name1</name>
</employee> 
 <employee>
 <age> 12 </age>
  <name> name1</name>
  <status>active</status>
</employee>

<employee>
 <age> 12 </age>
  <name> name1</name>
</employee></company>

Java 代码:

employeeList nList = doc.getElementsByTagName("employee");
     for (int i = 0; i < nList.getLength(); i++) {
            Node employeeNode= nList.item(i);
            employeeList employeeList = nNode.getChildNodes();
            Node insertNode=null;
            System.out.println(" Processing the " + i + " Portlet Tag");
                //Inner Loop to Process each Portlet tags   
                 int employeeList_Count=employeeList.getLength();

                 for (int j = 0; j < employeeList_Count; j++) {
                      Node childNode = employeeList.item(j);


                      if( childNode.getNodeName()) == "status")  {
                               removeNode(nNode,childNode);      //   assume remove functionality perfectly works (actually it is!!)
                      }
                      if ( j == employeeList_Count - 2)  // goes into loop during last node
                      {

                          Element insertElement = (Element)nNode;

                          insertElement.insertBefore(employee_status_element,  insertElement.getFirstChild().getNextSibling());  //employee_status_element,   this is the element should be inserted in all employee tags


                           doc.getDocumentElement().normalize();
                           updateXml2File(doc, xmlDTDPath , outputFile);    // functionality to write the xml into file
                      }

                }



          }

每次我运行此代码时,只有最后一名员工(3 名员工中)会更新元素“状态”...

这是输出的样子

第一个循环完成 标签在第一个员工标签中..在第二个循环中它被推到第二个。最后只有最后一个元素具有状态元素。

真的很奇怪...非常感谢您的指导。

【问题讨论】:

  • 不相关,但是..您缺少公司的结束标签。为什么要从employeeList_Count 中减去4?
  • 我无法理解您编写的例程。我建议您使用调试器逐步完成它,看看发生了什么。
  • 我仍然需要弄清楚为什么我添加了 -4,因为 count 会导致空指针异常。它包括为空的节点。公司标签关闭与此问题无关..但让我更正一下...

标签: java xml parsing dom


【解决方案1】:

我已经解决了这个问题。这很愚蠢,但在为代码加注了几个小时后后来被击中了。

以前的逻辑是这样的

Create Element
  Loop for Multiple Employees
        Attach/Append the Element to Employees

问题:元素仅附加到循环中的最后一个员工节点。

原因:由于我在循环之前只创建了一个元素.. 我无法将它附加到多个员工节点

解决方案有效:

现在我将创建的元素移动到循环中,然后它开始工作。

  Loop for Multiple Employees
        Create Element   
        Attach/Append the Element to Employees

我的问题和代码有点乱,我试图尽可能地纠正它以使其简单但无法......感谢每一位试图解决这个问题的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2012-04-14
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多