0

我使用 ServiceMix (Apache Camel),但在 StackOverFlow 上没有找到类似的主题。

我描述了顺序:

为了处理数据,我需要将 SQL 结果集转换为 XML。

4

1 回答 1

0

为了将数据库结果转换为 XML,我接下来要做:

数据库连接器 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>

骆驼路线:

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

将数据库响应转换为 XML 的 bean 代码

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();
}
于 2017-09-09T13:26:14.200 回答