我需要将一个文档(doc1)中的节点注册到另一个带有深层副本(属性,ns信息等)的文档(doc2),以便修复Java 8中的getElementById问题。 因此,我只需要在doc2中注册的那些节点,而不将它们附加到父节点中。 adoptNode和importNode Document API 的Document API需要将目标节点附加到doc2中,这会修改doc2的dom结构。是否有任何工作可以在不附加的情况下注册节点。
public void testAddNodesToDocument() throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
InputStream payloadData = new ByteArrayInputStream( "<Wrapper><TagA Id=\"attributeId\" Target=\"SomeTarges\">test</TagA></Wrapper>".getBytes() );
Document doc = builder.parse( payloadData );
setAttributeId( doc );
assertNotNull( doc.getElementById( "attributeId" ) );
Document newDoc = builder.newDocument();
Element nodeList = doc.getDocumentElement();
Node result = newDoc.importNode( nodeList, true );
// if appendChild is commnented out, the assertion of getElementById fails
// newDoc.appendChild( result );
setAttributeId(newDoc);
assertNotNull( "getElementsByTagName doesn't work, element is not imported!", newDoc.getElementsByTagName( "TagA" ) );
assertNotNull( "getElementById doesn't work!", newDoc.getElementById( "attributeId" ) );
}
private void setAttributeId( Document doc )
{
NodeList list = doc.getElementsByTagName( "*" );
for( int i = 0; i < list.getLength(); i++ )
{
Node node = list.item( i );
if( node.getNodeType() == Node.ELEMENT_NODE )
{
// do something with the current element
org.w3c.dom.Element item = (Element)node;
Attr idAttr = item.getAttributeNode( "Id" );
if( idAttr != null )
{
item.setIdAttributeNode( idAttr, true );
}
}
}
}