gpt4 book ai didi

java - 如何使用 Java 获取 XML 节点值?

转载 作者:行者123 更新时间:2023-12-02 03:22:04 29 4
gpt4 key购买 nike

<?xml version="1.0"?>
<events>
<event>
<id>1234567</id>
<Assets>
<Asset>
<UploadURL>
https://www.mkyong.com/java/how-to-construct-a-file-path-in-java/
</UploadURL>
<FTP>
<RequestDT>2016-02-29 12:36:52 -0500</RequestDT>
<ResponseDT>2016-02-29 12:36:58 -0500</ResponseDT>
</FTP>
<URL>
<Value>
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
</Value>
</URL>
</Asset>
</Assets>
</event>
</events>

Java 文件:

package src;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Users/mykong/Documents/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Staff id : " + eElement.getElementsByTagName("id").item(0).getTextContent());
System.out.println("First Name : " + eElement.getElementsByTagName("UploadURL").item(0).getTextContent());
// System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
// System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
// System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

我没有得到任何输出。我做错了什么吗?

最佳答案

嗯,xml文件没有这个节点。

  doc.getElementsByTagName("staff");

关于java - 如何使用 Java 获取 XML 节点值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39484731/

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