I'm trying to replace values of some attributes in an SVG file using StAX iterator API. I read an original file using
<?xml version="1.0" encoding="UTF-8"?>
In cases involving updating attributes, the best option is not using
XMLEventWriter, but instead finding positions (character offsets) of tags in XML files and make substring replacements. You can do it like this:
XMLEventReader, iterate through a file
XMLEvent#getLocation(), and then call
getCharacterOffset()on it, which will return the position in the original file, where this event was emitted.
Downside: You have to parse attributes manually, but this is trivial in most cases.
Also, I found an issue with
Characters events: they are reported after subsequent
</ is already consumed. For example, in
bar characters will be reported like
This may be different in other implementations of StAX, I'm using the default one from Java library. I assume this behavior can be explained by the fact that StAX parser never goes backwards, and when it has enough information to detect an end of characters event, it already consumes the beginning of a next element (opening or closing tag).
As for my original attempts to use
encodingon XML header can be added by explicitly constructing a new StartDocument event.