我有一个使用用户节点列表的 xml 文档。
有没有办法使用 StAX API 执行以下操作?
- 更新密码属性 [用于更改密码选项]
- 添加一个新的用户节点
在我看来,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 的引用才能对其进行更新。对于字符串,这应该很容易。对于 Stream 可能不是,因为一旦第一次读取流,它可能无法成为reset()
. 在执行原始解析时,您可能必须自己缓冲所有内容。并且您必须小心操作不会更改位置,否则后续操作会查看 XML 流中的错误位置。