如何从xom XML文档创建DatabaseChangeLog?

时间:2015-03-09 15:56:56

标签: liquibase

在进行一些程序内操作之后,我最终得到了一个包含我想要执行的ChangeLog的xom Document对象。根据我的理解,我必须在ChangeLogParser的帮助下将其转换为liquibase XML格式,ParsedNode。但是接口假定了解析方法中的外部表示。使用ResourceAccessor将Document对象注入解析器也是不可能的,因为方法getResourcesAsStream返回一组InputStream。 因此,我能想到使用liquibase基础结构的唯一方法是对String执行Document打印,并通过ByteArrayInputStream将其反馈给它。 或者我需要写一个独立的文档 - > ParsedNode转换器?

1 个答案:

答案 0 :(得分:0)

原来是一个明智的选择。在快速浏览一下SAX hander后,这很有效:

import liquibase.changelog.DatabaseChangeLog;
import liquibase.exception.SetupException;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.resource.ClassLoaderResourceAccessor;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import org.apache.commons.lang3.StringUtils;

/**
 * Convert a xom Document containing a liquibase changelog
 * to a DatabaseChangeLog.
 */
public class XOMDocumentToDatabaseChangeLogConverter {
    /**
     * Convert the Document ot a DatabaseChangeLog.
     * @param changeLogXML to convert.
     * @return contained changelog.
     * @throws SetupException on error.
     * @throws ParsedNodeException on error.
     */
    public static DatabaseChangeLog convert(Document changeLogXML) throws SetupException, ParsedNodeException {
        DatabaseChangeLog result = new DatabaseChangeLog();
        result.setPhysicalFilePath("");
        Element rootElement = changeLogXML.getRootElement();
        result.load(convert(rootElement), new ClassLoaderResourceAccessor());
        return result;
    }

    /**
     * Internal recursive method doing the node rollup.
     * @param element to convert.
     * @return converted node.
     * @throws ParsedNodeException on error.
     */
    protected static ParsedNode convert(Element element) throws ParsedNodeException {
        ParsedNode node = new ParsedNode(null, element.getLocalName());
        for (int i = 0; i < element.getAttributeCount(); ++i) {
            node.addChild(null, element.getAttribute(i).getLocalName(), element.getAttribute(i).getValue());
        }
        String seenText = element.getValue();
        if (!StringUtils.trimToEmpty(seenText).equals("")) {
            node.setValue(seenText.trim());
        }

        Elements children = element.getChildElements();
        for (int i = 0; i < children.size(); ++i) {
            node.addChild(convert(children.get(i)));
        }

        return node;
    }
}
相关问题