How to extract a fragment of an XML tree and save it into one single parameter

How to extract a fragment of an XML tree and save it into one single parameter

The quickest way to extract a fragment of an XML tree that matches a query criteria is to use lr_xml_extract() function. If the extracted fragment contains only nested elements (i.e. <a><b>Hello</b></a>), the function will save all of them into one single parameter named for example XMLFragmentParam.
If the extracted fragment however contains not only nested but sequential elements as well (i.e. <f></f><a><b>Hello</b></a>), all of them will be saved as separate parameters named for example XMLFragmentParam_1, XMLFragmentParam_2 etc, and XMLFragmentParam will be empty as shown in the example below:


lr_message("XMLFragmentParam: %s", lr_eval_string("{XMLFragmentParam}"));
//outputs XMLFragmentParam:
lr_message("XMLFragmentParam_1: %s", lr_eval_string("{XMLFragmentParam_1}"));
//outputs XMLFragmentParam_1: </f>
lr_message("XMLFragmentParam_2: %s", lr_eval_string("{XMLFragmentParam_2}"));
//outputs XMLFragmentParam_2: <a><b>Hello</b></a>

lr_xml_extract() does not allow saving of all sequential elements into one single parameter. If this is a requirement, there are two workarounds that could be used. Both however, require the execution of some custom C code:

1. Saving an XML fragment of sequential elements by using lr_xml_extract():

char str[1024];
char param_name[64];
int count;
int i;

count = lr_xml_extract("XML=<result><f></f><a><b>Hello</b></a></result>",

for(i = 1; i <= count; i++)
sprintf(param_name, "{XMLFragmentParam_%d}", i);
strcat(str, lr_eval_string(param_name));

lr_save_string(str, "XMLFragmentParam");
lr_message("XMLFragmentParam is: %s", lr_eval_string("{XMLFragmentParam}"));
//outputs XMLFragmentParam is: <f/><a><b>Hello</b></a>

2. Saving an XML Fragment of sequential elements by using lr_xml_transform() and xsl stylesheet:

char *stylesheet =
"<?xml version="1.0"?>"
"<xsl:stylesheet xmlns:xsl="" version="1.0">"
"<xsl:template match="/">"
"<xsl:for-each select="result">"
"<xsl:copy-of select="*"/>"

lr_save_string("<result><f></f><a><b>Hello</b></a></result>", "xml");

lr_message("Param: %s", lr_eval_string("{param}"));
//outputs Param: <f/><a><b>Hello</b></a>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s