gpt4 book ai didi

java - 读取 XML 文件并将其打印到控制台

转载 作者:行者123 更新时间:2023-11-30 02:19:36 24 4
gpt4 key购买 nike

我需要从我创建的 xml 文件中打印一些属性。

到目前为止,我受到 MKyoung 的启发,并对他的做了一些改变。但我无法获取 xml 属性。我想打印出“”中的名字和分数。

    <score name="Rasmus" score="10000"/>

我获取它的代码是:

public void readXMLFile() {
try {

File fXmlFile = new File("highscore.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("Highscore");

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("Name : " + eElement.getAttribute("score"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

我的名为 highscore.xml 的 xml 文件包含以下内容:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Highscore>
<score name="Rasmus" score="10000"/>
<score name="Søren" score="6000"/>
<score name="Niclas" score="5000"/>
</Highscore>

最佳答案

我已通过添加两行来编辑您的代码。检查下面。基本上,您必须迭代下一级节点。

代码:

public void readXMLFile() {
try {

File fXmlFile = new File("highscore.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Highscore");
Node child = nList.item(0);
NodeList nL = child.getChildNodes();
System.out.println("----------------------------");
int i = 1;
for (int temp = 0; temp < nL.getLength(); temp++) {
Node nNode = nL.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println(i + "," + eElement.getAttribute("name") + "," + eElement.getAttribute("score"));
i++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

输出:

Root element : Highscore
----------------------------
1,Rasmus,10000
2,Søren,6000
3,Niclas,5000

关于java - 读取 XML 文件并将其打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248018/

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