我有 2 个 Document 对象,其文档包含类似的 XML。例如:
<tt:root xmlns:tt="http://myurl.com/">
<tt:child/>
<tt:child/>
</tt:root>
还有一个:
<ns1:root xmlns:ns1="http://myurl.com/" xmlns:ns2="http://myotherurl.com/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:child/>
<ns1:child xsi:type="ns2:SomeType"/>
</ns1:root>
我需要将它们合并到具有 1 个根元素和 4 个子元素的 1 个文档中。
问题是,如果我使用 document.importNode
函数进行合并,它会正确处理除 xsi:type 元素之外的所有 namespace 。所以我得到的结果是:
<tt:root xmlns:tt="http://myurl.com/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tt:child/>
<tt:child/>
<ns1:child xmlns:ns1="http://myurl.com/"/>
<ns1:child xmlns:ns1="http://myurl.com/" xsi:type="ns2:SomeType"/>
</tt:root>
如您所见,ns2 在 xsi:type
中使用,但未在任何地方定义。有什么自动化的方法可以解决这个问题吗?
谢谢。
已添加:
如果使用默认的 Java DOM 库无法完成此任务,也许我可以使用其他一些库来完成我的任务?
最佳答案
如果我在您的第二个文件中修复了命名空间问题(通过绑定(bind)“xsi”前缀),并使用下面的代码进行合并,命名空间绑定(bind)将保留在输出中;或者至少它们在这里(Windows build 1.6.0_24 上的普通 Java 64 位)。
String s1 = "<!-- 1st XML document here -->";
String s2 = "<!-- 2nd XML document here -->";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware( true );
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc1 = builder.parse( new ByteArrayInputStream( s1.getBytes() ) );
Document doc2 = builder.parse( new ByteArrayInputStream( s2.getBytes() ) );
Element doc1root = ( Element )doc1.getDocumentElement();
Element doc2root = ( Element )doc2.getDocumentElement();
NamedNodeMap atts1 = doc1root.getAttributes();
NamedNodeMap atts2 = doc2root.getAttributes();
for( int i = 0; i < atts1.getLength(); i++ )
{
String name = atts1.item( i ).getNodeName();
if( name.startsWith( "xmlns:" ) )
{
if( atts2.getNamedItem( name ) == null )
{
doc2root.setAttribute( name, atts1.item( i ).getNodeValue() );
}
}
}
NodeList nl = doc1.getDocumentElement().getChildNodes();
for( int i = 0; i < nl.getLength(); i++ )
{
Node n = nl.item( i );
doc2root.appendChild( doc2.importNode( n, true ) );
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StreamResult streamResult = new StreamResult( System.out );
transformer.transform( new DOMSource( doc2 ), streamResult );
关于java - 在保留 xsi :type 的同时合并文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198485/