I'm trying to create a very function to read a very simple XML file and print its content on the QTCreator console.
I created the following XML file :
<SCANNERS>
<SCANNER>
<NAME>Test scanner</NAME>
<SERIAL>10102030</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 2</NAME>
<SERIAL>10102031</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 3</NAME>
<SERIAL>10102032</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 4</NAME>
<SERIAL>10102033</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 5</NAME>
<SERIAL>10102034</SERIAL>
</SCANNER>
</SCANNERS>
Then I created the following function, which is supposed to print each nodes inside each "SCANNER" tags :
void printDomDocument(QString xml)
{
QDomDocument xmlScanners;
QFile file(xml);
if (!file.open(QIODevice::ReadOnly))
{
std::cout << "QScannerEntryList : couldn't open XML file : " << xml.toStdString() << std::endl;
}
if (xmlScanners.setContent(&file))
{
QDomElement elem = xmlScanners.documentElement();
QDomNode n = elem.firstChild();
while (!n.isNull())
{
QDomElement e = n.toElement(); // try to convert the node to an element.
if (!e.isNull())
{
QDomNode n2 = e.firstChild();
std::cout << n2.nodeName().toStdString() << " " << n2.nodeValue().toStdString() << std::endl;
n2 = n2.nextSibling();
std::cout << n2.nodeName().toStdString() << " " << n2.nodeValue().toStdString() << std::endl;
}
n = n.nextSibling();
}
}
else
{
std::cout << "QScannerEntryList : couldn't grab content from XML file : " << xml.toStdString() << std::endl;
}
file.close();
}
My problem is, I can print the tagnames of each node perfectly, but for some reason I can't manage to print the values inside each of these tags. n2.nodeValue() doesn't show on the console.
Is there something I am doing wrong ?
Found out what's wrong.
Actually, the actual node value seems to be one node deeper than the child itself.
The solution is simply to "dig" one layer deeper :
QDomNode n2 = e.firstChild();
std::cout << n2.nodeName().toStdString() << " " << n2.firstChild().nodeValue().toStdString() << std::endl;
n2 = n2.nextSibling();
std::cout << n2.nodeName().toStdString() << " " << n2.firstChild().nodeValue().toStdString() << std::endl;
Returns the expected result :
NAME Test scanner
SERIAL 10102030
NAME Test scanner 2
SERIAL 10102031
NAME Test scanner 3
SERIAL 10102032
NAME Test scanner 4
SERIAL 10102033
NAME Test scanner 5
SERIAL 10102034
Related
File:
{
"somestring":{
"a":1,
"b":7,
"c":17,
"d":137,
"e":"Republic"
},
}
how can I read the somestring value by jsoncpp?
Use the getMemberNames() method.
Json::Value root;
root << jsonString;
Json::Value::Members propNames = root.getMemberNames();
std::string firstProp = propNames[0];
std::cout << firstProp << '\n'; // should print somestring
If you want to see all the properties, you can loop through it using an iterator:
for (auto it: propNames) {
cout << "Property: " << *it << " Value: " << root[*it].asString() << "\n";
}
This simple loop will only work for properties whose values are strings. If you want to handle nested objects, like in your example, you'll need to make it recursive, which I'm leaving as an exercise for the reader.
I have yahoo finance json file from which I want to isolate Date,Close and volume from the quote list and save it in the same order with a comma separtion in a single text file. This is my json script.
Json::Value root; // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse( YahooJson, root );
if(not parsingSuccessful)
{
// Report failures and their locations
// in the document.
std::cout<<"Failed to parse JSON"<<std::endl
<<reader.getFormatedErrorMessages()
<<std::endl;
return 1;
}else{
std::cout<<"\nSucess parsing json\n"<<std::endl;
std::cout << root<< std::endl;
std::cout <<"No of Days = "<< root["query"]["count"].asInt() << std::endl;
//below for loop returns an error
for (auto itr : root["query"]["result"]["quote"]) {
std::string val = itr.asString();
}
}
I was able to succed in fetching the json values and print root["query"]["count"].asInt() but when I go to the list values(quote) I dont know how to iterate through quote (query->result->quote) to get Date,close and volume values?
EDIT
Also tried this method
const Json::Value& quotes = root["query"]["results"]["quote"];
for (int i = 0; i < quotes.size(); i++){
std::cout << " Date: " << quotes[i]["Date"].asString();
std::cout << " Close: " << quotes[i]["Close"].asFloat();
std::cout << " Volume: " << quotes[i]["Volume"].asFloat();
std::cout << std::endl;
}
It works only when output was Date. For close and volume output it exits with a runtime error message and also this error
what() type is not convertible to string
You haven't specified which JSON library you are using, and I don't know the Yahoo finance data well enough to know the exact field names, but if you are using the JsonCpp library, which has documentation here, and you are asking about how to iterate over a JSON array, then one way to do it using iterators would look something like this
const Json::Value quote = root["query"]["results"]["quote"];
for (Json::ValueConstIterator itr = quote.begin(); itr != quote.end(); ++itr)
{
const Json::Value date = (*itr)["Date"];
const Json::Value close = (*itr)["Close"];
const Json::Value volume = (*itr)["Volume"];
std::cout << "Date: " << date.asString() << std::endl;
std::cout << "Close: " << close.asString() << std::endl;
std::cout << "Volume: " << volume.asString() << std::endl;
}
I am a newbie in pugixml. Consider I have XML given here. I want to get value of Name and Roll of Every Student. The code below only find the tag but not the value.
#include <iostream>
#include "pugixml.hpp"
int main()
{
std::string xml_mesg = "<data> \
<student>\
<Name>student 1</Name>\
<Roll>111</Roll>\
</student>\
<student>\
<Name>student 2</Name>\
<Roll>222</Roll>\
</student>\
<student>\
<Name>student 3</Name>\
<Roll>333</Roll>\
</student>\
</data>";
pugi::xml_document doc;
doc.load_string(xml_mesg.c_str());
pugi::xml_node data = doc.child("data");
for(pugi::xml_node_iterator it=data.begin(); it!=data.end(); ++it)
{
for(pugi::xml_node_iterator itt=it->begin(); itt!=it->end(); ++itt)
std::cout << itt->name() << " " << std::endl;
}
return 0;
}
I want the output of Name and Roll for each student. How can I modify above code? Also, if one can refer here(press Test), I can directly write xpath which is supported by pugixml. If so, how can I get the values I seek using Xpath in Pugixml.
Here's how you can do it with just Xpath:
pugi::xpath_query student_query("/data/student");
pugi::xpath_query name_query("Name/text()");
pugi::xpath_query roll_query("Roll/text()");
pugi::xpath_node_set xpath_students = doc.select_nodes(student_query);
for (pugi::xpath_node xpath_student : xpath_students)
{
// Since Xpath results can be nodes or attributes, you must explicitly get
// the node out with .node()
pugi::xml_node student = xpath_student.node();
pugi::xml_node name = student.select_node(name_query).node();
pugi::xml_node roll = student.select_node(roll_query).node();
std::cout << "Student name: " << name.value() << std::endl;
std::cout << " roll: " << roll.value() << std::endl;
}
I think that the reason why you are getting the "tags/nodes" instead of their values is because you are using the name() function instead of value(). Try replacing your itt->name() with itt->value() instead.
I found some good documentation about accessing document data here
Thanks #Cornstalks for the insight of using xpath in pugixml. I used child_value given here. The code of mine was thus:
for(pugi::xml_node_iterator it=data.begin(); it!=data.end(); ++it)
{
for(pugi::xml_node_iterator itt=it->begin(); itt!=it->end(); ++itt)
std::cout << itt->name() << " " << itt->child_value() << " " << std::endl;
}
I could also use xpath as #Cornstalks suggested thus making my code as:
pugi::xml_document doc;
doc.load_string(xml_mesg.c_str());
pugi::xpath_query student_query("/data/student");
pugi::xpath_query name_query("Name/text()");
pugi::xpath_query roll_query("Roll/text()");
pugi::xpath_node_set xpath_students = doc.select_nodes(student_query);
for (pugi::xpath_node xpath_student : xpath_students)
{
// Since Xpath results can be nodes or attributes, you must explicitly get
// the node out with .node()
pugi::xml_node student = xpath_student.node();
pugi::xml_node name = student.select_node(name_query).node();
pugi::xml_node roll = student.select_node(roll_query).node();
std::cout << "Student name: " << name.value() << std::endl;
std::cout << " roll: " << roll.value() << std::endl;
}
In your inner loop change the following line to get the values like :
student1 and 111 and so on...
std::cout << itt.text().get() << " " << std::endl;
This is the tag in XML
<content>The Avengers</content>
I want to take out "The Avengers" from the tag using xpath from libxml2 in C++
Here is my code
xmlXPathObject * xpathObj = xmlXPathEvalExpression( (xmlChar*)"/content", xpathCtx );
if ( xpathObj == NULL ) throw "failed to evaluate xpath";
for(int i=0;i<=0; i++)
{
xmlNode *node = NULL;
if ( xpathObj->nodesetval && xpathObj->nodesetval->nodeTab )
{
node = xpathObj->nodesetval->nodeTab[i];
std::cout << "Found the node we want" << std::endl;
}
else
{
throw "failed to find the expected node";
}
xmlAttr *attr = node->properties;
while ( attr )
{
std::cout << "Attribute name: " << attr->name << " value: " << attr->children->content << std::endl;
attr = attr->next;
}
xmlSetProp( node, (xmlChar*)"age", (xmlChar*)"3" );
}
Its work fine and reached easily at content tag but not showing the data between the tag
RESULT
<content age="3">The Avengers</content>
but in console its shows nothing
Found the node we want
Thanks
Firstly I would like to say that I have been using an XML parser written by Frank Vanden Berghen and recently trying to migrate to Pugixml. I am finding the transition bit difficult. Hoping to get some help here.
Question: How can I build a tree from scratch for the small xml below using pugixml APIs? I tried looking into the examples on the pugixml home page, but most of them are hard coded with root node values. what I mean is
if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;
is hard-coded. Also I tried reading about xml_document and xml_node documentation but could not figure out how to start with if I have to build a tree from scratch.
#include "pugixml.hpp"
#include <string.h>
#include <iostream>
int main()
{
pugi::xml_document doc;
if (!doc.load("<node id='123'>text</node><!-- comment -->", pugi::parse_default | pugi::parse_comments)) return -1;
//[code_modify_base_node
pugi::xml_node node = doc.child("node");
// change node name
std::cout << node.set_name("notnode");
std::cout << ", new node name: " << node.name() << std::endl;
// change comment text
std::cout << doc.last_child().set_value("useless comment");
std::cout << ", new comment text: " << doc.last_child().value() << std::endl;
// we can't change value of the element or name of the comment
std::cout << node.set_value("1") << ", " << doc.last_child().set_name("2") << std::endl;
//]
//[code_modify_base_attr
pugi::xml_attribute attr = node.attribute("id");
// change attribute name/value
std::cout << attr.set_name("key") << ", " << attr.set_value("345");
std::cout << ", new attribute: " << attr.name() << "=" << attr.value() << std::endl;
// we can use numbers or booleans
attr.set_value(1.234);
std::cout << "new attribute value: " << attr.value() << std::endl;
// we can also use assignment operators for more concise code
attr = true;
std::cout << "final attribute value: " << attr.value() << std::endl;
//]
}
// vim:et
XML:
<?xml version="1.0" encoding="UTF-8"?>
<d:testrequest xmlns:d="DAV:" xmlns:o="urn:example.com:testdrive">
<d:basicsearch>
<d:select>
<d:prop>
<o:versionnumber/>
<d:creationdate />
</d:prop>
</d:select>
<d:from>
<d:scope>
<d:href>/</d:href>
<d:depth>infinity</d:depth>
</d:scope>
</d:from>
<d:where>
<d:like>
<d:prop>
<o:name />
</d:prop>
<d:literal>%img%</d:literal>
</d:like>
</d:where>
</d:basicsearch>
</d:testrequest>
I could see most of the examples posted on how to read/parse the xml, but I could not find how to create one from the scratch.
Please refer to the following section of the manual https://github.com/zeux/pugixml/blob/master/docs/manual.html#manual.modify.add and to the following sample code https://github.com/zeux/pugixml/blob/master/docs/samples/modify_add.cpp
Home page of pugixml gives sample code for building XML tree from scratch.
Summary: Use default constructor for pugi::xml_document doc, then append_child for the root node. Generally, a node is first inserted. The insertion call's return value then serves as a handle for filling the XML node.
Constructing xml tree