Java 在没有DocumentBuilderFactory或DocumentBuilder的情况下将JDom 1.1.3元素转换为文档

Java 在没有DocumentBuilderFactory或DocumentBuilder的情况下将JDom 1.1.3元素转换为文档,java,xml,jdom,Java,Xml,Jdom,我需要找到一种更简单、更有效的方法将JDOM元素(及其所有定制节点)转换为文档ownerDocument()不起作用,因为这是版本JDOM 1 此外,org.jdom.IllegalAddException:内容已经有一个现有的父“root”异常在使用以下代码时发生 DocumentBuilderFactory dbFac = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFac.newDocumentBui

我需要找到一种更简单、更有效的方法将JDOM元素(及其所有定制节点)转换为
文档
ownerDocument()
不起作用,因为这是版本
JDOM 1

此外,
org.jdom.IllegalAddException:内容已经有一个现有的父“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);

我认为您必须使用以下元素的方法

Document doc = <element>.getDocument();
documentdoc=.getDocument();
参考上面写的


如果包含此父级的分支当前未附加到文档,则返回此父级的所属文档,或返回null。

JDOM内容一次只能有一个父级,您必须先将其从一个父级分离,然后才能附加到另一个父级。此代码:

如果该代码失败,那是因为
getElementFromDB()
方法返回的元素是其他结构的一部分。您需要“分离”它:

Element elementInfo = getElementFromDB();
elementInfo.detach();
Document doc = new Document(elementInfo);
好的,这就解决了
IllegalAddException

另一方面,如果您只想获取包含元素的文档节点,JDOM 1.1.3允许您通过以下方式实现:

请注意,该文档可能为空

要获取可用的最顶层元素,请尝试:

Element top = elementInfo;
while (top.getParentElement() != null) {
    top = top.getParentElement();
}
在您的例子中,您从DB获得的
elementInfo
是一个名为“root”的元素的子元素,类似于:

<root>
    <elementInfo> ........ </elementInfo>
</root>
Element top = elementInfo;
while (top.getParentElement() != null) {
    top = top.getParentElement();
}
<root>
    <elementInfo> ........ </elementInfo>
</root>
The Content already has an existing parent "root"