[英]Xml Builder with specific tags in java
I would like to build xml with special tags. 我想用特殊标签构建xml。 I tried to do it with Dom but it didn't work. 我尝试与Dom一起使用,但没有成功。
I would like to build this XML: 我想建立这个XML:
<om2m:ae xmlns:om2m="http://www.onem2m.org/xml/protocols">
<api>app-sensor</api>
<lbl>Type/sensor Category/temperature Location/home</lbl>
<rr>false</rr>
</om2m:ae>
How to i do this, what should i use? 我该怎么做,我应该怎么用?
I tried this code: 我尝试了这段代码:
public String XMLBuilder(String process, HashMap<String, String> mapHash) {
String returnVal = "";
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement;
if (process.equals("ae")) {
// root elements
rootElement = doc.createElementNS("http://www.onem2m.org/xml/protocols","m2m:ae");
doc.appendChild(rootElement);
}
Iterator it = mapHash.entrySet().iterator();
// Fill to xml
while (it.hasNext()) {
Map.Entry hashList = (Map.Entry) it.next();
Element val = doc.createElement(String.valueOf(hashList.getKey()));
val.appendChild(doc.createTextNode(String.valueOf(hashList.getValue())));
doc.appendChild(val);
}
// write the content into xml file
DOMSource source = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(source, result);
returnVal = writer.toString();
System.out.println(returnVal);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
return returnVal;
}
and i am getting error: 我得到错误:
org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
Change doc.appendChild(val);
更改doc.appendChild(val);
to doc.getDocumentElement().appendChild(val);
到doc.getDocumentElement().appendChild(val);
to insert the newly created elements as children of the root element. 插入新创建的元素作为根元素的子元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.