All, i have to make a call to third party service where it will return the response in XML, due to that i am not able to access the XML. is there any way to convert the XML response to json so that i can use in my project
i have tried this but i don't want to hard code my response
// Given an XML string
def xml = '''<root>
| <node>Tim</node>
| <node>Tom</node>
| <node>
| <anotherNode>another</anotherNode>
| </node>
|</root>'''.stripMargin()
// Parse it
def parsed = new XmlParser().parseText( xml )
// Deal with each node:
def handle
handle = { node ->
if( node instanceof String ) {
node
}
else {
[ (node.name()): node.collect( handle ) ]
}
}
// Convert it to a Map containing a List of Maps
def jsonObject = [ (parsed.name()): parsed.collect { node ->
[ (node.name()): node.collect( handle ) ]
} ]
// And dump it as Json
def json = new groovy.json.JsonBuilder( jsonObject )
// Check it's what we expected
assert json.toString() == '{"root":[{"node":["Tim"]},{"node":["Tom"]},{"node":[{"anotherNode":["another"]}]}]}'
Help appreciated.
Vikky, I had similar issue like this here is the code for your requirement, Place this code in PHP file say xmltojson.php
PHP CODE:
<?php
header('content-type: application/json; charset=utf-8');
if(strlen($_GET["feed"])>2)
{
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml)
{
$data = @simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[�callback�]}($json)" : $json;
}
}
?>
JQuery code :
/* Accessing the thirdparty data feed,converted xml to json using php and assigned the data to the model */
$.getJSON("xmltojson.php",{feed:"http://www.someurl.com/registerlistxml.asp?m=313"},function(data){
//put your code to access the json data
});
Hope this will solve your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.