How to read and write xml files?

前端 未结 6 524
庸人自扰
庸人自扰 2020-11-22 09:03

I have to read and write to and from an XML file. What is the easiest way to read and write XML files using Java?

6条回答
  •  灰色年华
    2020-11-22 09:44

    Writing XML using JAXB (Java Architecture for XML Binding):

    http://www.mkyong.com/java/jaxb-hello-world-example/

    package com.mkyong.core;
    
    import javax.xml.bind.annotation.XmlAttribute;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement
    public class Customer {
    
        String name;
        int age;
        int id;
    
        public String getName() {
            return name;
        }
    
        @XmlElement
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        @XmlElement
        public void setAge(int age) {
            this.age = age;
        }
    
        public int getId() {
            return id;
        }
    
        @XmlAttribute
        public void setId(int id) {
            this.id = id;
        }
    
    } 
    
    package com.mkyong.core;
    
    import java.io.File;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    
    public class JAXBExample {
        public static void main(String[] args) {
    
          Customer customer = new Customer();
          customer.setId(100);
          customer.setName("mkyong");
          customer.setAge(29);
    
          try {
    
            File file = new File("C:\\file.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    
            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
            jaxbMarshaller.marshal(customer, file);
            jaxbMarshaller.marshal(customer, System.out);
    
              } catch (JAXBException e) {
            e.printStackTrace();
              }
    
        }
    }
    

提交回复
热议问题