2

我正在使用 StAX 解析 XML 文件,并想知道每个标签的开始和结束位置。为此,我正在尝试使用getLocation().getCharacterOffset(),但它会为除第一个之外的每个标签返回不正确的值。

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(
        new StringReader("<root>txt1<tag>txt2</tag></root>"));

XMLEvent e;
e = reader.nextEvent(); // START_DOCUMENT
System.out.println(e);
System.out.println(e.getLocation());
e = reader.nextEvent(); // START_ELEMENT "root"
System.out.println(e);
System.out.println(e.getLocation());
e = reader.nextEvent(); // CHARACTERS "txt1"
System.out.println(e);
System.out.println(e.getLocation());
e = reader.nextEvent(); // START_ELEMENT "tag"
System.out.println(e);
System.out.println(e.getLocation());

上面的代码打印了这个:

<?xml version="null" encoding='null' standalone='no'?>
Line number = 1
Column number = 1
System Id = null
Public Id = null
Location Uri= null
CharacterOffset = 0

<root>
Line number = 1
Column number = 7
System Id = null
Public Id = null
Location Uri= null
CharacterOffset = 6

txt1
Line number = 1
Column number = 12
System Id = null
Public Id = null
Location Uri= null
CharacterOffset = 11

<tag>
Line number = 1
Column number = 16
System Id = null
Public Id = null
Location Uri= null
CharacterOffset = 15

之后<root>CharacterOffset正确的6,但之后txt111我期望看到10的。它究竟返回了什么偏移量?

4

1 回答 1

2

这可能是 Sun/Oracle 的 StAX 实现的错误/功能。使用 Woodstox,您会得到0, 0, 6, 10,这似乎是正确的。从http://wiki.fasterxml.com/WoodstoxHome下载 Woodstox,并将 JAR(woodstox-core + stax2-api)添加到您的类路径中。然后, XMLInputFactory将自动选择 Woodstox 实现。

于 2012-09-30T18:21:00.210 回答