当前位置: 代码迷 >> java >> Java读取XML文件并将特定标签放入列表
  详细解决方案

Java读取XML文件并将特定标签放入列表

热度:11   发布时间:2023-08-02 10:57:27.0

搜索了很长时间后,我找不到任何对我有帮助的东西。 (我也是java新手)

我有一个这样的 XML 文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Personen>
    <Person>
        <birthday>2002-03-01</birthday>
        <name>sad</name>
        <comment>Test Comment</comment>
    </Person>
    <Person>
        <birthday>1999-02-21</birthday>
        <name>Test1</name>
        <comment>Test Comment</comment>
    </Person>
    <Person>
        <birthday>2005-02-21</birthday>
        <name>Test2</name>
        <comment>Test Comment</comment>
    </Person>
</Personen>

我需要从文件中获取所有姓名和生日并将它们放入列表中:

$list->:
"sad","2002-03-01"
"Test1","1999-02-21"
"Test2","2005-02-21"

并且知道我完全不知道该怎么做。

找到这个并使用此代码后,我解决了我的问题

    try {

            File fXmlFile = new File("P:/example/exampleFile.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("Person");

            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(eElement.getElementsByTagName("name").item(0).getTextContent());
                    System.out.println(eElement.getElementsByTagName("birthday").item(0).getTextContent());

                }
            }
            } catch (Exception e) {
            e.printStackTrace();
            }
  相关解决方案