【问题标题】:How to copy a xml record from a xml file to another file using Java programming?如何使用 Java 编程将 xml 记录从 xml 文件复制到另一个文件?
【发布时间】:2019-03-11 19:47:34
【问题描述】:

我有一些xml记录如下

<records>
<record>
<name>SK</name>
<age>30</age>
</record>    

<record>
<name>KK</name>
<age>10</age>
</record>

<record>
<name>RK</name>
<age>50</age>
</record>

<record>
    <name>KB</name>
    <age>15</age>
    </record>

</records>

我使用 SAX Parser 来验证记录并消除

<records>
    <record>
    <name>SK</name>
    <age>30</age>
    </record>     

    <record>
    <name>RK</name>
    <age>50</age>  

   </record>
    </records>

我使用递归解析来提取标签和值,并验证年龄>20 的记录。但是,我不知道如何仅将年龄 > 20 的记录复制到另一个文件中。

有人可以帮忙吗?

Java 代码如下

// 从 xml 文件中提取标签

    private static void visit(Node node, int level) {
            NodeList list = node.getChildNodes();
            String nodeName = new String();
            String nodeValue = new String();
            // System.out.println(list);
            for (int i = 0; i < list.getLength(); i++) {
                Node childNode = list.item(i);
                if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    nodeName = childNode.getNodeName().toString();
                    System.out.println(nodeName);

                     if (PROPERTY_AGE.equals(nodeName)) {
                          nodeValue = childNode.getTextContent();
                      System.out.println(nodeName + " : " +                               nodeValue.trim());
                       int age = Integer.parseInt(nodeValue.trim());
                       if(age>20) {


     /* 
Here I would need to copy the current xml between <record></record> to another xml file. 
How can the entire record be extracted using Java?
*/

}
     } 
                        visit(childNode, level + 1);
                    }
                }
            }

        private static void readXMLFileAnddisplayTags(File inputXMLFile) {
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            try {

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                DefaultHandler handler = new DefaultHandler();
                InputStream inputStream = new FileInputStream(inputXMLFile);
                InputSource is = new InputSource(new InputStreamReader(inputStream, "UTF-8"));
                is.setEncoding("UTF-8");
                Document document = builder.parse(is);

                visit(document, 0);

            } catch (ParserConfigurationException | SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

【问题讨论】:

    标签: java xml file sax writer


    【解决方案1】:

    使用Jackson-XML-MapperNIO-APIStream-API,您只需几行代码即可实现目标。

     public static void main(String[] args) throws Exception {
        JacksonXmlModule module = new JacksonXmlModule();
        module.setDefaultUseWrapper(false);
        XmlMapper xmlMapper = new XmlMapper(module);
    
        Records input = xmlMapper.readValue(Files.newInputStream(Paths.get("./records.xml")), Records.class);
    
        List<Record> above20 = input.getRecord().stream()
          .filter(r -> r.getAge() > 20)
          .collect(Collectors.toList());
    
        Records output = new Records();
        output.setRecord(above20);
        String xml = xmlMapper.writeValueAsString(output);
        Files.write(Paths.get("./records2.xml"), xml.getBytes(StandardCharsets.UTF_8));
      }
    

    您只需为这两个 XML 元素定义两个类:

      class Records {    
        private List<Record> record;
    
        public List<Record> getRecord() {
          return record;
        }
        public void setRecord(List<Record> record) {
          this.record = record;
        }
      }
    
      class Record {
        private String name;
        private int age;
    
        public String getName() {
          return name;
        }
        public void setName(String name) {
          this.name = name;
        }
    
        public int getAge() {
          return age;
        }
        public void setAge(int age) {
          this.age = age;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多