2015-04-01 89 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" 
相关问题