Apache Camel How convert DB response to XML

1.4k views Asked by At

I use ServiceMix (Apache Camel) and I did not find a similar theme on StackOverFlow.

I describe the sequence:

For work with data I need convert SQL resultset to XML.

1

There are 1 answers

0
Mikro Koder On

For convert database result to XML I do next:

Database connector bean:

<bean
    class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/intertest"/>
    <property name="username" value="test"/>
    <property name="password" value="pass"/>
</bean>

Camel route:

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route id="_route1">
        <from id="_from1" uri="activemq:dev.input"/>
        <to id="_to1" uri="sql:SELECT * FROM h4_rs4?dataSource=dataSource"/>
        <bean id="_bean1" method="transform" ref="myTransform"/>
        <to id="_to2" uri="activemq:queue:dev.output"/>
    </route>
</camelContext>

Code of bean which convert database response to XML

try {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("DBResult");
    doc.appendChild(rootElement);

    ArrayList rsRowsArray = (ArrayList) body; // Responce
    Iterator<LinkedHashMap> rsRowsIterator = rsRowsArray.iterator();
    while (rsRowsIterator.hasNext()) {

        Element row = doc.createElement("row");
        rootElement.appendChild(row);

        Attr attr = doc.createAttribute("id");
        attr.setValue("1");
        row.setAttributeNode(attr);

        LinkedHashMap rsRow = rsRowsIterator.next(); 
        // LOGGER.info("Полей в строке = " + rsRow.size());
        Set fieldsNames = rsRow.keySet(); // Get fields name
        Iterator<String> fieldsIterator = fieldsNames.iterator();
        while (fieldsIterator.hasNext()) {
            String fieldName = fieldsIterator.next();
            Element field = doc.createElement(fieldName);
            field.appendChild(doc.createTextNode(rsRow.get(fieldName).toString()));
            row.appendChild(field);
        }
    }
    return doc;
} catch (ParserConfigurationException pce) {
    pce.printStackTrace();
}