用Java读取特定的xml文件

时间:2015-12-27 15:01:27

标签: java xml file parsing

我会用Java读取和解析两个文件。第一个如下:

<add>
    <doc>
        <field name="id">name123</field>
        <field name="date">1998-01-06 03:31:00</field>
        <field name="text"> text text text </field>
    </doc>
</add>

第二个,如下所示:

<top>

<title>
title title

<documents>
nameDocument1
</top>

<top>

<title>
title title title

<documents>
nameDocument1
nameDocument2
</top>

我必须阅读第一个变量"id", "data" and "text"的两个对象,第二个变量"title", "listDocument"

我尝试过XML解析器,任何人都可以帮我实现Java解决方案吗?

1 个答案:

答案 0 :(得分:1)

更改文件路径,一切正常

   public static void main(String argv[]) {

    try {

        File fXmlFile = new File("//test.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("doc");
        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("First Name : " + eElement.getElementsByTagName("field").item(0).getTextContent());
                System.out.println("Date : " + eElement.getElementsByTagName("field").item(1).getTextContent());
                System.out.println("Text : " + eElement.getElementsByTagName("field").item(2).getTextContent());

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

输出:   名字:name123   日期:1998-01-06 03:31:00   文字:文字文字