如何部分解析XML(只有1级深)

时间:2014-02-13 23:27:56

标签: java xml jaxb unmarshalling stax

输入(fullInput

想象一下,我有以下内容作为InputStream(或从该流读取的内存中的String):

<?xml version="1.0" ?>
<root>
    <element attr="val1"><x /><y /></element>
    <element attr="val2"><y /></element>
    <element attr="val3"><x /><x /></element>
    <element attr="val4"><z /><y /></element>
</root>

我想如何使用解决方案(bridgeXml

IProprietaryUnmarshaller UNMARSHALLER = ...;
List<Element> parseFullXml(String fullInput) throws UnmarshallException {
    List<String> inputs = bridgeXml(fullInput);
    List<Element> outputs = new ArrayList();
    for(String input : inputs) {
         Element e = UNMARSHALLER.unmarshall(input);
         outputs.add(e);
    }
    return outputs;
}

我在找什么

我正在寻找bridgeXml的/ idea实现,其中输入String / *Stream被分成较小的字符串,这些字符串是格式良好的XML文档(没有XML声明)。

我想避免的简单实现

以下实现容易出错,不灵活且不应该使用,我正在寻找使用某种库或XML解析器的正确实现!

List<String> bridgeXml(String input) {
    // strip anything up to the opening root element, and LTrim the remainder
    input = input.replaceAll("(?s)^.*<root.*?>\\s*", "");
    // strip anything after the closing root element, and RTrim the remainder
    input = input.replaceAll("(?s)\\s*</root.*$", "");
    // split at </element> closing tags, not removing them (?<= does the magic)
    return Arrays.asList(input.split("(?<=</element>)"));
}

限制

  • 无法更改XML输入,并且XML输入是完全有效的XML。
  • 必须使用专有的unmarshaller,不能修改。
  • 我正在寻找一种解决方案,其中文件不是XML解组,XML编组,专有解组。
  • (不要选择XML / Java代码样式,格式,可见性修饰符等! 这些是简化的代码,便于沟通。)

解决方案(编辑)

我最后写了这篇文章......我最终对XML进行了双重解析(参见getOuterXml),因为现在认为它很慢是不成熟的。我之后有一个巨大的数据库查询,速度慢了。

protected <T> List<T> read(InputStream inputStream, String tagName) throws XMLStreamException,
    TransformerException, DecodingException
{
    List<T> result = new ArrayList<T>();
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader = xmlFactory.createXMLStreamReader(inputStream, "ISO-8859-1");
    while (xmlReader.hasNext()) {
        xmlReader.next();
        if (xmlReader.isStartElement() && tagName.equals(xmlReader.getLocalName())) {
            String output = getOuterXml(xmlReader);
            @SuppressWarnings("unchecked")
            T object = (T) UNMARSHALLER.unmarshall(output);
            result.add(object);
        }
    }
    return result;
}

protected String getOuterXml(XMLStreamReader xmlr) throws TransformerException
{
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new StAXSource(xmlr), new StreamResult(stringWriter));
    return stringWriter.toString();
}

protected <T> List<T> getObjects(String urlString, String tagName)
{
    LOG.info("Downloading [{}] updates from [{}].", tagName, urlString);
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    try {
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        inputStream = conn.getInputStream();
        return read(inputStream, tagName);
    } catch (Exception ex) {
        String exceptionMessage = "Updating [" + tagName + "] from [" + urlString + "] failed.";
        LOG.error(exceptionMessage, ex);
        throw new MyFancyWrapperException(exceptionMessage, ex);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                LOG.warn("Cannot close HTTP's input stream", ex);
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

所以这里有一个用于示例xml的litte stax解析器:

String xml = "<root><element>test</element></root>";
XMLInputFactory xmlif = XMLInputFactory.newInstance();
XMLStreamReader xmlr = xmlif.createXMLStreamReader(new StringReader(xml));
while (xmlr.hasNext()) {
    xmlr.next();
    if (xmlr.isStartElement() || xmlr.isEndElement()) {
        System.out.println(xmlr.getLocalName() + " " + xmlr.getEventType());
    }
}

在这里你会找到一个解释,你如何将stax与jaxb结合起来。

http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html