XML/XPath: Difference between revisions

1,728 bytes added ,  6 years ago
(Added Kotlin)
Line 208:
);</lang>
 
=={{header|C}}==
{{libheader|LibXML}}
Takes XML document and XPath expression as inputs and prints results, usage is printed if invoked incorrectly.
<lang C>
/*Abhishek Ghosh, 10th March 2018*/
 
#include <libxml/parser.h>
#include <libxml/xpath.h>
 
xmlDocPtr getdoc (char *docname) {
xmlDocPtr doc;
doc = xmlParseFile(docname);
 
return doc;
}
 
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
 
context = xmlXPathNewContext(doc);
 
result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
 
return result;
}
int main(int argc, char **argv) {
 
char *docname;
xmlDocPtr doc;
xmlChar *xpath = (xmlChar*) argv[2];
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar *keyword;
if (argc <= 1) {
printf("Usage: %s <XML Document Name> <XPath expression>\n", argv[0]);
return(0);
}
 
docname = argv[1];
doc = getdoc(docname);
result = getnodeset (doc, xpath);
if (result) {
nodeset = result->nodesetval;
for (i=0; i < nodeset->nodeNr; i++) {
xmlNodePtr titleNode = nodeset->nodeTab[i];
keyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);
printf("Value %d: %s\n",i+1, keyword);
xmlFree(keyword);
}
xmlXPathFreeObject (result);
}
xmlFreeDoc(doc);
xmlCleanupParser();
return 0;
}
</lang>
testXML.xml contains the XML mentioned in the task description. Code must be compiled with the correct flags.
<pre>
C:\rosettaCode>xPather.exe testXML.xml //price
Value 1: 14.50
Value 2: 23.99
Value 3: 4.95
Value 4: 3.56
 
C:\rosettaCode>xPather.exe testXML.xml //name
Value 1: Invisibility Cream
Value 2: Levitation Salve
Value 3: Blork and Freen Instameal
Value 4: Grob winglets
</pre>
=={{header|C sharp}}==
<lang csharp>XmlReader XReader;
503

edits