2

I am trying to transform a JSON object to XML, but i have somehow get stuck in jscript (not an expert). Here is the code:

...
var GEOJSON_PARSER = new OpenLayers.Format.GeoJSON();
var vectorLayerAsJson = GEOJSON_PARSER.write(vlayer.features);
    ...
var x2js = new X2JS();
    ...
var xmlDocStr2 = x2js.json2xml_str(vectorLayerAsJson);
alert(xmlDocStr2);
    ...
// JSON arrays to string
var xmlDoc1 = x2js.json2xml_str({
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {},
        "geometry": {
            "type": "Polygon",
            "coordinates": [
                [
                    [22580, -24812],
                    [24772, -28076],
                    [27732, -24204],
                    [22580, -24812]
                ]
            ]
        }
    }]
});
alert(xmlDoc1);

In the first case the json2xml_str(vectorLayerAsJson) function returns something like a JSON object however in the second it returns the correct XML.

Both objects are identical "vectorLayerAsJson" is the one declared as "type":"FeatureCollection ..." in the second case.

I have also tried alternate ways of calling x2js.json2xml_str such as x2js.json2xml_str($.parseJSON($("vectorLayerAsJson").val())); with no success!

Any ideas?

3 Answers 3

1

It seems you are not aware Openlayers 2 is already able to write your features to XML based formats, so I'm not sure using x2js is useful (but I don't know your use case)

It can be KML, GPX, GML v2, GML v3. Those are all subsets of XML.

Read the API docs for more.

You can see a sample using your code to create GML (you can also look at Vector Formats Example)

var gml_parser_v2 = new OpenLayers.Format.GML.v2();
var gml_parser_v3 = new OpenLayers.Format.GML.v3();

vector_layer_as_gml_v2 = gml_parser_v2.write(vlayer.features);
vector_layer_as_gml_v3 = gml_parser_v3.write(vlayer.features);

console.log(vector_layer_as_gml_v2);
console.log(vector_layer_as_gml_v3);
0

are you sure your json file is well formed? try here http://www.utilities-online.info/xmltojson/#.Uql7VyeQMRc and verify first that the conversion works correctly.

1
  • If i alert my initial Json file, copy and paste its contents to this online tool, there is no problem!
    – thanili
    Commented Dec 16, 2013 at 13:18
0

First, be sure you don't have an UTF-8 BOM into your file. A one-liner command available here can spot and suppress it.

Another option could be switching to another js lib conversion such as JSONXML.

(If you want further support, please upload file and code online)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.