我需要创建一个dom文档:
<namespace:Facturae xmlns:namespace="URI1" xmlns:namespace2="URI2">
//<.......
</namespace:Facturae>
但以下代码产生错误:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
代码是:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
Element FacturaeElement = document.createElementNS("URI1", "Facturae");
document.appendChild(FacturaeElement);
FacturaeElement.setPrefix("namespace"); //First namespace OK
FacturaeElement.setAttributeNS("URI2", "xmlns:namespace2", "aaa"); //Generate error
//Rest of code
如何将第二个命名空间放入元素?
答案 0 :(得分:0)
搜索更多信息我已达成解决方案:
我使用普通的setAtribute方法(没有命名空间)来指示带有xmlns前缀的属性的名称,所以:&#34; xmlns:namespace2&#34;。
然后,我用这个命名空间创建子元素,然后加上前缀。
Element FacturaeElement = document.createElementNS("URI1", "Facturae");
document.appendChild(FacturaeElement);
FacturaeElement.setPrefix("namespace"); //First namecpace
FacturaeElement.setAttribute("xmlns:namespace2", "URI2"); //second namespace
//I create the subelement with a namespace
Element FileHeaderElement = document.createElementNS("URI2", "FileHeader");
FacturaeElement.appendChild(FileHeaderElement);
FileHeaderElement.setPrefix("namespace2");