gpt4 book ai didi

Java XML 空节点

转载 作者:行者123 更新时间:2023-12-01 14:39:35 26 4
gpt4 key购买 nike

XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
<Employee type="permanent">
<Name>Ali</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
<Employee type="contract">
<Name>Hasan</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
<Employee type="permanent">
<Name>Ahmet</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Personnel>

XML.java:

public class XML{
DocumentBuilderFactory dfk;
Document doc;
public void xmlParse(String xmlFile) throws
ParserConfigurationException, SAXException,
IOException {
dfk= DocumentBuilderFactory.newInstance();
doc= dfk.newDocumentBuilder().parse(new File(xmlFile));
xmlParse();
}

public void xmlParse(){
doc.getDocumentElement().normalize();
Element element = doc.getDocumentElement();
NodeList nodeList = element.getElementsByTagName("Personnel");

for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
}
}
}

大家好;我如何获取姓名、ID、年龄等。我尝试了更多次但不起作用,我只显示空..抱歉我的英语不好..(XML文件>正确<)

最佳答案

您可以尝试此方法来获取元素及其子元素。这只是为了帮助您入门:

 public void xmlParse(String xmlFile) throws ParserConfigurationException, SAXException,IOException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File(xmlFile));
xmlParse(document.getDocumentElement());
}

private void xmlParse(Element node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
String value = currentNode.getNodeName();
System.out.print(value + " "); // prints Employee

NodeList nodes = currentNode.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node cnode = nodes.item(j);
System.out.print(cnode.getNodeName() + " ");//prints:name, id, age
}
System.out.println();
}
}

输出为:

#text 
Employee #text Name #text Id #text Age #text
#text
Employee #text Name #text Id #text Age #text
#text
Employee #text Name #text Id #text Age #text
#text

关于Java XML 空节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114378/

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