[英]How do I add a namespace prefix to an XML DOM object?
I am trying to build an XML document using a specific namespace. 我正在尝试使用特定的命名空间构建XML文档。 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>
Here is what i have so far. 这是我到目前为止所拥有的。
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>
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完全如第一个带有命名空间前缀的XML示例和带有命名空间前缀的标记所示?
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. 我正在尝试创建一个XML字符串,该字符串将用于Spring-WS Web服务,该服务器需要一个JAXB对象,该对象的格式如第一个示例所示。
You can use setPrefix
. 您可以使用
setPrefix
。
But it is better to create the root element like this: 但最好像这样创建根元素:
document.createElementNS("http://www.myschema.com", "m:documentObject");
Note also that passing null
to createElement
is a supported way of forcing a null namespace. 另请注意,将
null
传递给createElement
是一种强制null命名空间的受支持方式。 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. 在您的原始示例中,这将无法工作,因为您的文档元素通过组合没有前缀的命名空间URI有效地强制默认命名空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.