简体   繁体   English

使用Java从子节点Xml获取所有值

[英]get all values from child node Xml with Java

I'm trying to parse an XML file to make out of it excel file by using Java 我正在尝试使用Java解析XML文件以使其制成excel文件
and I can't understand how to retrieve all child nodes like these names ? 而且我不明白如何检索这些名称的所有子节点?

   <Products>
        <companies>
            <name>Al Rawabi</name>
            <name>Al Rifai</name>
            <name>Colgate-Palmolive</name>
            <name>Danone (Nutrition)</name>
            <name>Henkel</name>
        </companies>
    <Products>

I tried to make it this way, but as a result I'm getting an empty lists of names. 我试图用这种方法来做,但是结果是我得到了一个空的名字列表。

    NodeList ListOfProducts = xmlDoc.getElementsByTagName("Products"); //first we need to find total number of Products blocks
    int totalProducts = ListOfProducts.getLength();
        System.out.println("Total no of Products : " + totalProducts);
    for(int s = 0; s < ListOfProducts.getLength(); s++)
    {
        Node ProductsNode = listOfProducts.item(s);
        System.out.println("Products number : " + s);
        if (ProductsNode.getNodeType() == Node.ELEMENT_NODE)
        {
            Element ProductElement = (Element) ProductsNode;
            NodeList CompanyList = ProductElement.getElementsByTagName("companies"); // find node companies
            System.out.println("companies number : " + CompanyList.getLength());
            for(int cl = 0; cl < CompanyList.getLength(); cl++) {
                NodeList CompanyNameList = CompanyList.item(cl).getChildNodes();
                for (int j = 0; j < CompanyNameList.getLength(); j++) {
                    Node childNode = CompanyNameList.item(j);
                    if ("name".equals(childNode.getNodeName())) {
                        for (int nl = 0; nl < CompanyNameList.getLength(); nl++) {
                            Element CompanyNameElement = (Element) CompanyNameList.item(nl);
                            NodeList textFNList = CompanyNameElement.getChildNodes();
                            System.out.println("Company: " + nl + " :" + (textFNList.item(0)).getNodeValue().trim());
                            CompaniesNames.add((textFNList.item(0)).getNodeValue().trim());
                        }
                    }
                }
            }
        }// end of if clause
    }// end of for loop with s var
//load the xml file
function loadDoc(){
    //create the xml request
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           myFunction(this);
        }
    };
    //open and send the request
    xhttp.open("GET", "filename.xml", true);
    xhttp.send();
}

//print the xml data in html
function myFunction(xml) {
    var i;
    var xmlDoc = xml.responseXML; //xml file loaded
    var x = xmlDoc.getElementsByTagName("companies");
    //loop through xml element
    for (i = 0; i < x.length; i++) {
        x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
    }
}

This is the JavaScript version of doing you want to do. 这是您要执行的JavaScript版本。 Hope you can use some of it in Java! 希望您可以在Java中使用它!

Below is how you can do it in XPath and VTD-XML. 下面是如何在XPath和VTD-XML中进行操作。 Beware that I am the author of VTD-XML so my pov may be biased. 请注意,我是VTD-XML的作者,因此我的观点可能有偏见。

import com.ximpleware.*;

public class extractName{
   public static void main(String s[]) throws VTDException{

          VTDGen vg = new VTDGen();
          if (!vg.parseFile("input.xml",false))
             return false;
          VTDNav vn = vg.getNav();
          AutoPilot ap =new AutoPilot(vn);
          ap.selectXPath("/Products/companies/names/text()");
          int i=0;
          while((i=ap.evalXPath())!=-1){
              System.out.println(" name is ===>"+vn.toString(i));
          }

   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM