gpt4 book ai didi

java - java中带有特定标签的Xml Builder

转载 作者:行者123 更新时间:2023-12-01 09:24:20 25 4
gpt4 key购买 nike

我想用特殊标签构建 xml。我尝试与 Dom 一起做,但没有成功。

我想构建这个 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>

我该如何做到这一点,我应该使用什么?

我尝试了这段代码:

 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;
}

我收到错误:

org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 

最佳答案

doc.appendChild(val); 更改为 doc.getDocumentElement().appendChild(val); 以将新创建​​的元素插入为根元素的子元素。

关于java - java中带有特定标签的Xml Builder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39959427/

25 4 0
文章推荐: regex - 为什么我在 NLTK RegexpTokenizer() 中的正则表达式删除了 "is"和 "to"?
文章推荐: python - BeautifulSoup:如何提取
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com