我有一个xml文档,其中我使用了用户节点列表。
有没有办法使用StAX API执行以下操作?
答案 0 :(得分:1)
在我看来,StAX听起来不是最简单的选择。但是......
XMLStreamReader接口有getLocation()
方法,因此当您遇到感兴趣的XML字符串的一部分时,您可以维护之后要执行的操作列表以及你应该执行它们。
所以粗略的伪代码:
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();
}
当然,Action需要传递对原始XML String / Stream的引用才能更新它。对于String,这应该很容易。对于Stream可能没有,因为一旦第一次读取了流,它可能无法成为reset()
。在执行原始解析时,您可能必须自己缓冲所有内容。而且你必须要小心,这些操作不会改变位置,否则后续的Actions会查看XML流中的错误位置。