[英]Appending an XML element using StaX
我有一個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流中看到錯誤的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.