如何在XML DOM对象中添加命名空间前缀? [英] How do I add a namespace prefix to an XML DOM object?
问题描述
我正在尝试使用特定的命名空间来构建一个XML文档。我想要生成的最终文档应该是这样的:
I am trying to build an XML document using a specific namespace. The final document I am trying to generate is supposed to look like this:
<m:documentObject xmlns:m="http://www.myschema.com">
<sender>token</sender>
<receiver>token</receiver>
<payload>token</payload>
</m:documentObject>
这是我到目前为止。
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element requestElement = document.createElementNS("http://www.myschema.com", "documentObject");
document.appendChild(requestElement);
Element sender = document.createElement("sender");
requestElement.appendChild(sender);
Text senderText = document.createTextNode("Xmlsender");
sender.appendChild(senderText);
Element receiver = document.createElement("receiver");
requestElement.appendChild(receiver);
Text receiverText = document.createTextNode("Xmlreceiver");
receiver.appendChild(receiverText);
Element payload = document.createElement("payload");
requestElement.appendChild(payload);
Text payloadText = document.createTextNode("Xmlpayload");
payload.appendChild(payloadText);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(requestElement);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.transform(source, result);
String xmlString = sw.toString();
System.out.println(xmlString)
由于某些原因,当我运行上述模式没有前缀出来。如下所示:
For some reason when I run the above the schema comes out without the prefix. As shown below:
<?xml version="1.0" encoding="utf-8"?>
<documentObject xmlns="http://www.myschema.com">
<sender>Xmlsender</sender>
<receiver>Xmlreceiver</receiver>
<payload>Xmlpayload</payload>
</documentObject>
我需要做什么才能使XML完全如第一个具有命名空间的XML示例所示前缀和标签具有命名空间前缀?
What do I need to do so that XML is exactly as shown in the first XML example with the namespace prefix and the tags to have the namespace prefix?
我正在尝试创建一个XML字符串,该字符串将用于Spring-WS webservice,该Web服务器希望使用第一个示例中显示的格式的JAXB对象。
I am trying to create an XML string which will be used for a Spring-WS webservice which expects a JAXB object which is in the format shown in the first example.
推荐答案
您可以使用 setPrefix
。
You can use setPrefix
.
但是最好创建这样的根元素:
But it is better to create the root element like this:
document.createElementNS("http://www.myschema.com", "m:documentObject");
另请注意,通过 null
至 createElement
是一种强制使用空命名空间的支持方式。在您的原始示例中,这不会起作用,因为您的文档元素通过将名称空间URI与前缀组合来有效地强制使用默认命名空间。
Note also that passing null
to createElement
is a supported way of forcing a null namespace. In your original example this would however not work because your document element effectively forces a default namespace by combining a namespace URI with no prefix.
这篇关于如何在XML DOM对象中添加命名空间前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!