1

Can you tell me best way to read an XML file in Java with sample code? XML content be like below.

<table sourceName="person" targetName="person">
       <column sourceName="id" targetName="id"/>
       <column sourceName="name" targetName="name"/>``
</table>

4 Answers 4

3

I would use JAXB, try this, it works

public class Test1 {
    @XmlAttribute
    String sourceName;
    @XmlAttribute
    String targetName;
    @XmlElement(name = "column")
    List<Test1> columns;

    public static Test1 unmarshal(File file) {
        return JAXB.unmarshal(file, Test1.class);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is a helpful but incomplete answer. It should add the necessary imports and show where the JAXB variable comes from. This works for me: import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.*; JAXBContext jaxbContext = JAXBContext.newInstance(Test1.class); Unmarshaller JAXB = jaxbContext.createUnmarshaller(); return JAXB.unmarshal(file, Test1.class); within an exception-handling block: try { ... } catch (JAXBException e) { ... }
1

You could use Simple form simple XML serialization:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class App {

    public static void main(String[] args) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "<table sourceName=\"person\" targetName=\"person\">\n"
                + "    <column sourceName=\"id\" targetName=\"id\"/>\n"
                + "    <column sourceName=\"name\" targetName=\"name\"/>``\n"
                + "</table>";
        Serializer serializer = new Persister();
        Table table = serializer.read(Table.class, xml);
        System.out.println(table.getSourceName());
        System.out.println(table.getTargetName());
        for (Column colunmn : table.getColumns()) {
            System.out.println(colunmn.getSourceName());
            System.out.println(colunmn.getTargetName());
        }
    }
}

Table:

import java.util.List;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name = "table")
public class Table {

    @Attribute
    private String sourceName;
    @Attribute
    private String targetName;
    @ElementList(name = "column", inline = true)
    private List<Column> columns;

    public Table() {
    }

    public String getSourceName() {
        return sourceName;
    }

    public void setSourceName(String sourceName) {
        this.sourceName = sourceName;
    }

    public String getTargetName() {
        return targetName;
    }

    public void setTargetName(String targetName) {
        this.targetName = targetName;
    }

    public List<Column> getColumns() {
        return columns;
    }

    public void setColumns(List<Column> columns) {
        this.columns = columns;
    }
}

Column:

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;

@Root(name = "column")
public class Column {

    @Attribute
    private String sourceName;
    @Attribute
    private String targetName;

    public Column() {
    }

    public String getSourceName() {
        return sourceName;
    }

    public void setSourceName(String sourceName) {
        this.sourceName = sourceName;
    }

    public String getTargetName() {
        return targetName;
    }

    public void setTargetName(String targetName) {
        this.targetName = targetName;
    }
}

Comments

0

Since it's a very small XML file, I would use DOM parsing, you can find a full example here:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

But in essence:

File fXmlFile = new File("/Users/mkyong/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

NodeList nList = doc.getElementsByTagName("table");

for (int temp = 0; temp < nList.getLength(); temp++) {
    Node tableNode = nList.item(temp);
    Element tableElement = (Element) tableNode;

    System.out.println("Table source name: " + tableElement.getAttribute("sourceName"));
    System.out.println("Table target name: " + tableElement.getAttribute("targetName"));

    NodeList columnList = tableElement.getElementsByTagName("column");
    for (int j = 0; j < columnList.getLength(); j++) {
        Node columnNode = columnList.item(j);
        Element columnElement = (Element) columnNode;

        System.out.println("Column source name: " + columnElement.getAttribute("sourceName"));
        System.out.println("Column target name: " + columnElement.getAttribute("targetName"));


    }
}

Please see the relevant imports at the top of the example.

Hope it helps, A.

2 Comments

Hi, my config file contains multiple table configurations, I have to read table associated columns and need to some process. Config file looks like <tableConfig> <table sourceName="person" targetName="person"> <column sourceName="id" targetName="id"/> <column sourceName="name" targetName="name"/> </table> <table sourceName="dept" targetName="dept"> <column sourceName="deptId" targetName="id"/> <column sourceName="deptName" targetName="name"/> </table> </tableConfig>
I've edited my answer accordingly: first you iterate over tables, then over columns.
0

Books have been written on the subject, and it all depends. JAXB is a good choice if the structure of the file is simple and stable (it maps elements/attributes to Java classes, and you don't want to be changing and recompiling your Java classes three times a week).

Otherwise there's a range of generic tree models - DOM is the most widely used, oldest, and worst; I would recommend JDOM2 or XOM.

But the ideal is to avoid reading the data into Java at all; the "XRX" or "end-to-end XML" principle is to use XML-oriented languages such as XSLT and XQuery for the entire application, perhaps calling into Java support routines occasionally if you really need to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.