0

The below code reads xml file and would need to have that written into file ( using java). Can someone help ?.

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;
  }
}

and xml file is

<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>

Output I'm getting now

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

Need help in writing this into config.properties files

Makoto
  • 104,088
  • 27
  • 192
  • 230

1 Answers1

0

This isn't the place for helping with JAXB (because the question has to do with writing out the properties file), but here you go.

You need a node that wraps the customer. This node is now the root element. You need to annotate it as such, and you need to bind the wrapper when creating the JAXB context.

Customers:

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;
    }
}

Customer:

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;
    }
}

Main:

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();
        }

    }
}
Isaiah van der Elst
  • 1,435
  • 9
  • 14
  • Awesome. Thanks so much sir for this is ...a great help!. I'm so glad that I'll now be in right direction as the application is heavily utilizing xml. – user2029529 Feb 13 '15 at 17:11