1
我想通過使用Java解析一個XML文件,使其使用Java
我無法理解如何檢索像這些名稱的所有子節點?從Java子節點Xml中獲取所有值
<Products>
<companies>
<name>Al Rawabi</name>
<name>Al Rifai</name>
<name>Colgate-Palmolive</name>
<name>Danone (Nutrition)</name>
<name>Henkel</name>
</companies>
<Products>
我試圖這樣做,但結果我得到一個空的名稱列表。
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
據我所知Apache POI的工作原理在DOM等內存樹中,這就是爲什麼我開始使用DOM;但是我對任何其他Java解決方案都很開放,以後我可以使用POI來製作我的Excel文件 –