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);
}
}
}
大家好 我怎么能得到名字,身份证,年龄等我尝试更多次但不工作我只显示null .. 索里因为我的英语不好.. (XML文件&gt;正确&lt;)
答案 0 :(得分:1)
您可以尝试这样来获取元素及其子元素。这只是为了帮助您入门:
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