gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:11:13 26 4
gpt4 key购买 nike

我正在尝试使用 Java 解析 XML 文件以将其生成 excel 文件
我不明白如何检索像这些名称这样的所有子节点?

   <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 中使用其中的一些!

关于java - 使用Java从子节点Xml中获取所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com