Y
Y
YV2014-09-04 16:47:18
Java
YV, 2014-09-04 16:47:18

Parsing XML with XMLStreamReader. How to get current cursor position?

You need to add tags to the XML file, and the formatting, comments, etc., should remain the same, after which half of the libs immediately disappear, the other half is not stacked under the license. As a result, it was decided to use the capabilities of javax.xml.stream.* .
Initially, the algorithm was as follows:
1. I look for the desired tag by name + parent path(ie "/organization/customers")
2. If I find it, then I do found = true
3. Then I wait for the tag to be non-empty and write like this:

switch (reader.next()) {
                //...
                case XMLStreamConstants.CHARACTERS:
                    if (src == null) {
                        src = reader.getTextCharacters();
                    }
                    if (found) {
                        result.append(src, 0, reader.getTextStart());
                        result.append(newContent);
                        final int offset = reader.getTextStart() + reader.getTextLength();
                        result.append(src, offset, src.length - offset);
                        applied = true;
                    }
                    break;
            }
}

which seems to be ok.
But here in the XMLStreamReader spec I see this:
By default entity references must be expanded and reported transparently to the application. An exception will be thrown if an entity reference cannot be expanded. If element content is empty (ie content is "") then no CHARACTERS event will be reported.

Well, this is nothing because there is a method reader.getElementText().isEmpty()and then you can organize logic regarding XMLStreamConstants.START_ELEMENT, XMLStreamConstants.END_ELEMENT, it can also be organized in a similar way and if the required tag is missing, but there is one problem:
reader.getTextStart() - is only in XMLStreamConstants.CHARACTERS , how then to find out the position of the tag, for example, with XMLStreamConstants.END_ELEMENT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
YV, 2014-09-04
@targetjump

ByteArrayInputStream + reader.getLocation().getCharacterOffset()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question