【问题标题】:Java read XML file and put specific tags into listJava读取XML文件并将特定标签放入列表
【发布时间】:2019-02-19 13:32:24
【问题描述】:

搜索了很长时间后,我找不到任何对我有帮助的东西。 (我也是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"

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

【问题讨论】:

标签: java xml


【解决方案1】:

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

    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();
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多