使用java从xml获取元素和属性

时间:2017-04-27 18:53:37

标签: java xml parsing

我无法弄清楚如何在另一个xml标记内获取xml标记的属性和元素 例如:     如果我有这个xml部分:     

<echo>-----------------------------------------</echo>
<echo>Applying ${app} .msi file... </echo>
<echo>-----------------------------------------</echo>

<exec executable="start" vmlauncher="false">
<arg line='/wait ${basedir}\Installation\${pkgname}.msi' />
</exec>
</target>


<target name="repackage" depends="program,update,move_shortcuts"
description="Installs and updates ${app}" />

<target name="program" unless="executableExists">
<echo>---------------------------------------------------------</echo>
<echo> Installing ${app} </echo>
<echo>---------------------------------------------------------</echo>

<unzip src="${install_pkg}" dest="c:\" /> 

<echo>---------------------------------------------------------</echo>
<echo> ...PROGRAM INSTALLATION IS COMPLETE. </echo>
<echo>---------------------------------------------------------</echo>
<sleep seconds="1" />
</target>

我希望打印出类似

的内容
 Current Element :target
 name : install
 depends : repackage
 unless : 
 description : 
 command: exec executable = start , vmlauncher = false
       arg line='/wait ${basedir}\Installation\${pkgname}.msi'

现在我正在使用这种方法     NodeList tarList = doc.getElementsByTagName(“target”);

System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++");
         System.out.println("");
         System.out.println("");
         for (int tarTemp = 0; tarTemp < tarList.getLength(); tarTemp++) {
            Node tarNode = tarList.item(tarTemp);
            System.out.println("\nCurrent Element :" 
               + tarNode.getNodeName());



            if (tarNode.getNodeType() == Node.ELEMENT_NODE) {
               Element eElement = (Element) tarNode;
               System.out.println("name : " 
                  + eElement.getAttribute("name"));
               System.out.println("depends : " 
                      + eElement.getAttribute("depends"));
               System.out.println("unless : " 
                          + eElement.getAttribute("unless"));
               System.out.println("description : " 
                          + eElement.getAttribute("description"));
               System.out.println(
                            eElement.getTextContent());


               }

         }

并产生此输出

 Current Element :target
 name : install
 depends : repackage
 unless : 
 description : 

现在,如果我想在此输出中包含命令,我不能,因为tarList只查找标记名称“target”中的元素和属性。

1 个答案:

答案 0 :(得分:0)

您需要按照处理target的相同方式解析要包含在target中的标记的节点:

if (tarNode.getNodeType() == Node.ELEMENT_NODE) {
    Element eElement = (Element) tarNode;
    NodeList internalNodes = eElement .getElementsByTagName("commmand");
    //process internalNodes 
    for (Element el : internalNodes)
    { 
       ...
    }
    ...