我正在使用 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
,但之后txt1
是11
我期望看到10
的。它究竟返回了什么偏移量?