简体   繁体   中英

Appending an XML element using StaX

I have an xml document in which I use list of user nodes.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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