我正在尝试用Java创建包含以下元素的XML文档:
<project xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2"
xmlns:acme="http://www.acme.com/schemas"
color="blue">
我知道如何创建项目Node。我也知道如何使用
来设置color属性element.setAttribute("color",
"blue")
我是否使用setAttribute()以相同的方式设置xmlns和xmlns:acme属性,或者由于它们是名称空间属性,所以我是否以某种特殊方式进行设置?
我相信您必须使用:
element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:acme", "http://www.acme.com/schemas");
我认为以下代码不会解决问题!
myDocument.createElementNS("http://www.imsglobal.org/xsd/ims_qtiasiv1p2","project");
这将创建以下元素(使用DOM)
<http://www.imsglobal.org/xsd/ims_qtiasiv1p2:project>
因此,这不会将名称空间属性添加到元素。因此,使用DOM我们可以执行类似的操作>]
Element request = doc.createElement("project"); Attr attr = doc.createAttribute("xmlns"); attr.setValue("http://www.imsglobal.org/xsd/ims_qtiasiv1p2"); request.setAttributeNode(attr);
因此它将像下面那样设置第一个属性,您可以用相同的方式设置多个属性
<project xmlns="http://www.imsglobal.org/xsd/ims_qtiasiv1p2>
您可以在创建元素时简单地指定名称空间。例如:
[对我而言,唯一有效的方法是在2019年使用attr()方法: