0

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文件>正确<)

4

1 回答 1

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 
于 2013-04-19T23:19:25.817 回答