2

我有一个方法可以编写这样的 XML- 文件:

private void doProcess() {

    Element rootElement = mDoc.createElement("Test");
    mDoc.appendChild(rootElement);

....... I build the whole document here... 
}

但是这个方法可以被多个线程调用,例如,如果两个线程同时调用这个方法,我会得到一个

): org.w3c.dom.DOMException: Only one root element allowed

我已经尝试过使用可重入锁,但这没有用......有人可以给我一个提示吗?

编辑:

我不使用多个线程构建文档...每次调用我的方法都会构建自己的文档...所以有时在我的应用程序中可能会同时调用我的方法两次...而且有我的问题...

4

2 回答 2

2

In the question you state:

I dont build the Document with multiple Threads...Every Call of my Method builds his own Doc

Currently the code given shares a single doc between all calls to the function. In order to have each call to the function work on it's own document, you need to modify the code such that each call has it's own doc.

This can be done either by creating and returning a new document object

private XMLDocument doProcess() {
  XMLDocument mDoc = new XMLDocument(); // or simmilar depending on XML library
  Element rootElement = mDoc.createElement("Test");
  mDoc.appendChild(rootElement);

  // ....... I build the whole document here... 

  return mDoc; //return the document object
}

Or, by passing the document object in as a parameter

private void doProcess(XMLDocument mDoc) { ... }
于 2013-10-31T09:13:05.260 回答
1

一个 xml 可以只有一个根,所以这可能是您的问题的答案。您可以在此方法之外实例化一个根元素,并每次将元素添加到此根内部方法中。

于 2013-10-31T08:39:27.873 回答