使用 Java 读取 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10310777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:30:04  来源:igfitidea点击:

Read XML files with Java

javaxmlxml-parsingxmldom

提问by Bishan

I need to read a XML file with java. File structure as below.

我需要用 java 读取 XML 文件。文件结构如下。

<?xml version="1.0" encoding="UTF-8"?>
<xml_tool xmlns:md="http://www.example.com/XT/1.0/">
    <md:header>
        <md:application_version>1.0</md:application_version>
        <md:export_date>19-04-2012</md:export_date>
        <md:export_time>14:55</md:export_time>
        <md:export_user>USER01</md:export_user>
    </md:header>
    <md:table table_name="CUSTOMER" key="customer number" record_count="2" column_count="5">
        <md:record>
            <md:column name="customer_number">123456</md:column>
            <md:column name="reg_date">01-04-2012</md:column>
            <md:column name="customer_name">Test Customer</md:column>
            <md:column name="customer_type">Normal </md:column>
            <md:column name="comments">This is a test record</md:column>
        </md:record>
        <md:record>
            <md:column name="customer_number">555111</md:column>
            <md:column name="reg_date">02-04-2012</md:column>
            <md:column name="customer_name">Test Customer</md:column>
            <md:column name="customer_type">VIP </md:column>
            <md:column name="comments">This is a test record</md:column>
        </md:record>
    </md:table>
</xml_tool>

I have read How to read XML file in Java – (DOM Parser)example and try to do my work. But I'm unable to read XML file successfully.

我已阅读How to read XML file in Java – (DOM Parser)示例并尝试完成我的工作。但我无法成功读取 XML 文件。

My Code

我的代码

    try {

        File fXmlFile = new File("c:\file.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("md:record");

        for (int i = 0; i < nList.getLength(); i++) {

            Node node = nList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) node;

                System.out.println(getTagValue("md:column", eElement));


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

 private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

            Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
      }

and Result is

结果是

123456
555111

How could I read this XML file?

我怎么能读取这个 XML 文件?

回答by Sachin Mhetre

Update your for loop...

更新你的 for 循环...

for (int i = 0; i < nList.getLength(); i++)
{
      Node node = nList.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE)
      {                 
             if(eElement.hasChildNodes())
             {
                 NodeList nl = node.getChildNodes();
                 for(int j=0; j<nl.getLength(); j++)
                 {
                     Node nd = nl.item(j);
                     System.out.println(nd.getTextContent());
                 }
             }
       }
} 

回答by rob

Currently you're doing very inexact queries (namely, getElementsByTagName(...), which is not restricted to first-level descendants). In getTagValue(...), you'll need to iterate over the NodeListin order to get all the data for all of the children--in which case, maybe you intend for the method to return a List<String>. Or, better yet, move that NodeListto your other method and loop over it there.

目前您正在执行非常不精确的查询(即,getElementsByTagName(...)不限于一级后代)。在 中getTagValue(...),您需要遍历NodeList以获取所有子项的所有数据——在这种情况下,您可能打算让该方法返回一个List<String>. 或者,更好的是,将其移动NodeList到您的其他方法并在那里循环。

To get all the data, including the header, you will need to recursively iterate over all the elements, starting with the root node.

要获取包括标题在内的所有数据,您需要从根节点开始递归迭代所有元素。

That said, there's a much better way. You can use JAXBto bind your XML schema to your POJO (plain-old Java object) data model. Then all the loading will be done automatically, and you can concentrate on the program logic.

也就是说,有一个更好的方法。您可以使用JAXB将 XML 模式绑定到 POJO(普通 Java 对象)数据模型。然后所有的加载都会自动完成,你可以专注于程序逻辑。