2015-04-01 72 views
2

我需要找到將JDOM元素(及其所有定製節點)轉換爲Document的更簡單高效的方法。 ownerDocument()將不起作用,因爲這是JDOM 1版本。在沒有DocumentBuilderFactory或DocumentBuilder的情況下將JDom 1.1.3元素轉換爲文檔

此外,org.jdom.IllegalAddException: The Content already has an existing parent "root"使用下面的代碼時發生異常。

DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFac.newDocumentBuilder(); 
Document doc = null; 
Element elementInfo = getElementFromDB(); 
doc = new Document(elementInfo); 
XMLOutputter xmlOutput = new XMLOutputter(); 
byte[] byteInfo= xmlOutput.outputString(elementInfo).getBytes("UTF-8"); 
String stringInfo = new String(byteInfo); 
doc = dBuilder.parse(stringInfo); 

回答

1

我認爲你必須使用下面的元素的方法。

Document doc = <element>.getDocument(); 

請參考API documentation它說

返回此父的擁有文檔或NULL如果含有這種父分支目前沒有連接到一個文檔。

0

JDOM內容一次只能有一個父對象,並且必須先將其從一個父對象中進行分解,然後才能將其附加到另一個父對象上。此代碼:

Document doc = null; 
Element elementInfo = getElementFromDB(); 
doc = new Document(elementInfo); 

如果該代碼失敗,這是因爲getElementFromDB()方法返回一個元素是一些其它結構的一部分。你需要「分離」是:

Element elementInfo = getElementFromDB(); 
elementInfo.detach(); 
Document doc = new Document(elementInfo); 

OK,即解決了IllegalAddException

在另一方面,如果你只是想獲得包含該元素的文檔節點,JDOM 1.1.3允許你與getDocument

Document doc = elementInfo.getDocument(); 

請注意,該文檔可能爲空。

,獲得可用的最頂端的元素,嘗試:

Element top = elementInfo; 
while (top.getParentElement() != null) { 
    top = top.getParentElement(); 
} 

在你的情況,你elementInfo你從DB是一個元素的子稱爲「根」,是這樣的:

<root> 
    <elementInfo> ........ </elementInfo> 
</root> 

這就是爲什麼你在它讓你做的消息,字「根」:

The Content already has an existing parent "root" 
相關問題