将一些特定的值从xml写入java中的属性文件

时间:2015-02-12 20:11:52

标签: java xml

以下代码读取xml文件,需要将其写入文件(使用java)。有人可以帮忙吗?。

package com.test.learning;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMParserDemo {

  public static void main(String[] args) throws Exception {
    //Get the DOM Builder Factory
    DocumentBuilderFactory factory =
      DocumentBuilderFactory.newInstance();

    //Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();

    //Load and Parse the XML document
    //document contains the complete XML as a Tree.
    Document document =
      builder.parse(
        ClassLoader.getSystemResourceAsStream("employee.xml"));


    List < Employee > empList = new ArrayList < > ();

    //Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();

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

      //We have encountered an <employee> tag.
      Node node = (Node) nodeList.item(i);
      if (node instanceof Element) {
        Employee emp = new Employee();
        emp.id = node.getAttributes().
        getNamedItem("id").getNodeValue();

        NodeList childNodes = node.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
          Node cNode = (Node) childNodes.item(j);

          //Identifying the child tag of employee encountered. 
          if (cNode instanceof Element) {
            String content = cNode.getLastChild().
            getTextContent().trim();
            switch (cNode.getNodeName()) {
              case "firstName":
                emp.firstName = content;
                break;
              case "lastName":
                emp.lastName = content;
                break;
              case "location":
                emp.location = content;
                break;
            }
          }
        }
        empList.add(emp);
      }

    }
    //System.out.println(nodeList.getLength());
    //Printing the Employee list populated.
    for (Employee emp: empList) {
      System.out.println(emp);


    }

  }
}

class Employee {
  String id;
  String firstName;
  String lastName;
  String location;

  @
  Override
  public String toString() {
    return firstName + " " + lastName + "(" + id + ")" + location;
  }
}

和xml文件是

<employees>
  <employee id="111">
    <firstName>Rakesh</firstName>
    <lastName>Mishra</lastName>
    <location>Bangalore</location>
  </employee>
  <employee id="112">
    <firstName>John</firstName>
    <lastName>Davis</lastName>
    <location>Chennai</location>
  </employee>
  <employee id="113">
    <firstName>Rajesh</firstName>
    <lastName>Sharma</lastName>
    <location>Pune</location>
  </employee>
</employees>

输出我现在正在

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

需要帮助将其写入config.properties文件

1 个答案:

答案 0 :(得分:0)

这不是帮助JAXB的地方(因为这个问题与写出属性文件有关),但是你走了。

您需要一个包装客户的节点。此节点现在是根元素。您需要对其进行批注,并且在创建JAXB上下文时需要绑定包装器。

客户:

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;


@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customers {

    @XmlElement(name="customer")
    private List<Customer> customers;

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }
}

客户:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;

@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlAttribute
    private int id;
    private int age;
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

主:

import java.io.File;
import java.util.Arrays;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    public static void main(String... args) {

        Customer customer1 = new Customer();
        customer1.setId(100);
        customer1.setName("Mohammad");
        customer1.setAge(29);

        Customer customer2 = new Customer();
        customer2.setId(200);
        customer2.setName("Ashfaq");
        customer2.setAge(30);

        Customers customers = new Customers();
        customers.setCustomers(Arrays.asList(customer1, customer2));

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(Customers.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);


            jaxbMarshaller.marshal(customers, System.out);

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

    }
}