开发者

Appending an XML element using StaX

开发者 https://www.devze.com 2023-04-01 12:32 出处:网络
I have an xml document in which I use list of user n开发者_运维技巧odes. Is there a way to do the following using StAX API?

I have an xml document in which I use list of user n开发者_运维技巧odes.

Is there a way to do the following using StAX API?

  1. update password attribute [for change password option]
  2. add a new user node


StAX doesn't sound like the easiest option to do what you're asking in my opinion. However ...

The XMLStreamReader interface has a getLocation() method, so when you encounter a part of the XML String that you find interesting, you could maintain a List of actions to perform afterwards, along with the location where you should perform them.

So in rough pseudo-code:

while (parsing) {
    int event = xmlStreamReader.next();
    if (isEventPasswordAttribute(event)) {
        // create an Action to update password attribute,
        // passing in xmlStreamReader.getLocation() and other necessary parameters
    } else if (isTimeToAddNewUserNode(event)) {
        // create an Action to add new user
        // passing in xmlStreamReader.getLocation() and other necessary parameters
    }
} // end parse

...

for (Iterator<Action> it = actions.iterator(); it.hasNext(); ) {
    Action action = it.next();
    action.perform();
}

The Action of course needs to be passed a reference to the original XML String/Stream in order to update it. For a String this should be easy. For a Stream possibly not, as once the stream has been read the first time it may not be able to be reset(). You may have to buffer all the contents yourself as you're performing the original parse. And you would have to be careful that the actions don't alter the locations, otherwise subsequent Actions would look at the wrong place in the XML stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号