简体   繁体   English

Java:在XMLStreamReader2上设置属性?

[英]Java: Set attributes on XMLStreamReader2?

I'm using Woodstox to stream XML documents in my application. 我正在使用Woodstox在应用程序中流式传输XML文档。 I need to set default attributes on elements as defined by the schema before they are processed, but the only way to do this with Woodstox is to read the document into memory with an extra XMLStreamReader with some logic to write the default attributes, write it out to an in-memory XML document, and then pass the in-memory document into the business-logic. 我需要在架构定义的元素上设置默认属性,然后再对其进行处理,但是使用Woodstox进行此操作的唯一方法是使用额外的XMLStreamReader将文档读入内存,并带有一些逻辑来写入默认属性,并将其写出到内存XML文档中,然后将内存文档传递到业务逻辑中。

I don't like this. 我不喜欢这样 I want to stream the document per element to keep the memory footprint low because the documents can be potentially big and I'm running multiple instances of this in the application. 我想按元素流式传输文档,以保持较低的内存占用,因为文档可能很大,并且我正在应用程序中运行多个实例。 Is there a way to inject attributes into the XMLStreamReader while streaming the document? 有没有一种方法可以在流式传输文档时将属性注入XMLStreamReader中? I already found a way to skip over nodes I'm not interested in while streaming: 我已经找到一种方法来跳过流式传输时不感兴趣的节点:

public class XMLPreProcessor extends StreamReader2Delegate {
    public XMLPreProcessor(XMLStreamReader2 sr) {
        super(sr);
    }

    //Skip over all processing instructions
    //Can this be extended to inject attributes to elements?
    @Override
    public int next() throws XMLStreamException {
        int eventType = super.next();

        while(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) {
            eventType = super.next();
        }

        return eventType;
    }
}

Can this delegate be tweaked to inject attributes into the XMLStreamReader? 可以调整此委托以将属性注入XMLStreamReader吗?

No I don't think there is such facility to inject content. 不,我认为没有这种设施可以注入内容。 If you were using Event API ( XMLEventReader ), you could probably modify element objects, however. 如果使用事件API( XMLEventReader ),则可能可以修改元素对象。

However: your approach, using delegate, might work. 但是:使用委托的方法可能有效。 You would need to override all methods that access attributes, and keep state of additional attributes. 您将需要覆盖所有访问属性的方法,并保持其他属性的状态。 So when asked how many attributes there are, you'd return original count plus injected attributes; 因此,当被问到有多少个属性时,您将返回原始计数加上注入的属性; and probably virtually append new ones after original. 并可能会在原始内容之后追加虚拟内容。 This sounds doable; 这听起来可行; you may also need to override next() to update state whenever START_ELEMENT is read, discard after advancing. 每当读取START_ELEMENT ,您可能还需要覆盖next()来更新状态,前进后将其丢弃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM