簡體   English   中英

具有Java中特定標簽的Xml Builder

[英]Xml Builder with specific tags in java

我想用特殊標簽構建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); 插入新創建的元素作為根元素的子元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM