Java XML Null Node



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,年龄等。我尝试了更多的时间,但没有工作,我只显示null..对不起,我的英语不好。(XML文件)正确<</strong>

您可以尝试这样获取元素及其子元素。这只是为了帮助你开始:

 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 

最新更新