从Java子节点Xml中获取所有值
问题描述:
我想通过使用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
答
//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;
}
}
这是做你想要做的JavaScript版本。希望你可以在Java中使用它!
答
下面介绍如何在XPath和VTD-XML中执行此操作。注意我是VTD-XML的作者,所以我的偏见可能会有所偏差。
据我所知Apache POI的工作原理在DOM等内存树中,这就是为什么我开始使用DOM;但是我对任何其他Java解决方案都很开放,以后我可以使用POI来制作我的Excel文件 –