【问题标题】:reading out all Parent nodes of XML in java在java中读取XML的所有父节点
【发布时间】:2015-12-05 03:50:28
【问题描述】:

我有一个如下的 XML:

<parent>
     <child1>
     </child1>
     <child2>
     </child2>
</parent>
<parent>
     <child3>
     </child3>
     <child4>
     </child4>
</parent>

我可以使用下面的代码读取第一个父节点的子节点值:

// Get the staff element by tag name directly
            Node PatientVariables = doc.getElementsByTagName("parent").item(0);

            // loop the staff child node
            NodeList patientlist = PatientVariables.getChildNodes();

            for (int i = 0; i < patientlist.getLength(); i++) {
                   Node node = patientlist.item(i);
                 if ("child1".equals(node.getNodeName())) {
                     PatientLastNameValue=node.getTextContent();
                    //System.out.println("The XML value:"+node.getTextContent() );
                   }

但我无法读取第二个父节点值(child3 和 child4)

【问题讨论】:

    标签: java xml dom javax.xml


    【解决方案1】:

    您需要遍历 xml 并将每个父级添加到数组中。

    Node [] PatientVariables = add.doc.getElementsByTagName("parent");
    

    您需要遍历父级,并通过每个父级的子级进行嵌套循环。

    for( int i = 0; i< PatientVariables.length; i++){
      // loop the staff child node
      NodeList patientlist = PatientVariables[i].getChildNodes();
    
            for (int i = 0; i < patientlist.getLength(); i++) {
                   Node node = patientlist.item(i);
            /.../
    

    这是一个基本的想法。

    【讨论】:

      【解决方案2】:

      以及上面@Johannes 的回答,这一行

      Node PatientVariables = doc.getElementsByTagName("parent").item(0);
      

      仅返回第一个 &lt;parent&gt;...&lt;/parent&gt; 实例。

      您应该将doc.getElementsByTagName("parent") 视为一个集合并对其进行迭代。

      【讨论】:

        【解决方案3】:

        XML 只允许一个根节点。将您的“父”节点放在根节点下,如下所示:

        <root>
            <parent>
            ...
            </parent>
            <parent>
            ...
            </parent>
        </root>
        

        然后在根的子节点上进行交互。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多