Create XML document on GWT client side

时光总嘲笑我的痴心妄想 提交于 2019-12-05 19:36:56

Here is an example. To generate the following xml :

<root>
  <node1 attribute="test">
     my value
  </node1>
  <node2 attribute="anothertest"/>
</root>

You have to write the following code on the Java client side :

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.XMLParser;

public static void main(String[] args) {
    Document doc = XMLParser.createDocument();

    Element root = doc.createElement("root");
    doc.appendChild(root);

    Element node1 = doc.createElement("node1");
    node1.setAttribute("attribute","test");
    node1.appendChild(doc.createTextNode("my value"));
    doc.appendChild(node1);

    Element node2 = doc.createElement("node2");
    node2.setAttribute("attribute","anothertest");
    doc.appendChild(node2);

    System.out.println(doc.toString());
}

Well ok, your anser works but some things to append.

First you have to include

<inherits name="com.google.gwt.xml.XML" />

in your *gwt.xml file (http://blog.elitecoderz.net/gwt-and-xml-first-steps-with-comgooglegwtxmlerste-schritte-mit-gwt-und-xml-unter-comgooglegwtxml/2009/05/ )

second you use the following namespaces:

import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.XMLParser;
user2232206

Accepted answer is right, but there is a little mistake on it, node1 and node2 should be linked to root, not to doc.

So this line:

doc.appendChild(node1);

should really be:

root.appendChild(node1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!