I want to use Poco::JSON in my project to convert the received json from server to XML format for manipulation in the code . I have'nt yet tried Poco::JSON. Please provide some pointer to accomplish this.
Here is a quick implementation of JSON to XML handler. Use it (with caution, this is not production code) like this:
#include "JSON2XMLConverter.h"
#include "Poco/JSON/Parser.h"
using Poco::JSON::Parser;
using Poco::JSON::Handler;
int main()
{
std::string json = "{ \"name\" : \"Homer\", \"age\" : 38, \"wife\" : \"Marge\", \"age\" : 36, \"children\" : [ \"Bart\", \"Lisa\", \"Maggie\" ] }";
Handler::Ptr pJ2XConv = new JSON2XMLConverter(std::cout);
Parser(pJ2XConv).parse(json);
return 0;
}
Output (formatting added, not generated by code):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>Homer</name>
<age>38</age>
<wife>Marge</wife>
<age>36</age>
<children>
<children1>Bart</children1>
<children2>Lisa</children2>
<children3>Maggie</children3>
</children>
</root>
Related
I have a configuration file saver/loader. In addition to the expected data, there is a <CustomData> node. When saving the node, we'd simply have a std::string _customData and add it to the node, like this:
pugi::xml_document doc;
pugi::xml_node config = doc.append_child("OurConfig");
// save custom data
pugi::xml_node customData = config.append_child("CustomData");
customData.append_child(pugi::node_pcdata).set_value(_customData);
Our _customData was base64 encoded XML. It is provided from another part of the application. It must be a string, since the other part of the application uses different programming language (C#). As you can imagine, that became annoying, because it wasn't human readable. First step to fix this was simply to get rid of base64 in the app that provides _customData. So now we have readable version, which looks like this:
<?xml version="1.0"?>
<OurConfig>
<CustomData><CfgRoot>
<SomeValue name="External setting for foo" value="Foo"/>
<SomeValue name="External setting for bar" value="Bar"/>
</CfgRoot></CustomData>
</OurConfig>
But it could probably improve if the custom data was directly appended to XML tree instead of as string value. How can I append XML string as XML and not as string to pugixml tree?
Ie. the output I'd like:
<?xml version="1.0"?>
<OurConfig>
<CustomData>
<CfgRoot>
<SomeValue name="External setting for foo" value="Foo"/>
<SomeValue name="External setting for bar" value="Bar"/>
</CfgRoot>
</CustomData>
</OurConfig>
In the docs, there are three methods listed. I used the first one, making a convenience function like this:
bool AppendXMLString(pugi::xml_node target, const std::string& srcString)
{
// parse XML string as document
pugi::xml_document doc;
if (!doc.load_buffer(srcString.c_str(), srcString.length()))
return false;
for (pugi::xml_node child = doc.first_child(); child; child = child.next_sibling())
target.append_copy(child);
return true;
}
RDF4J Newbie question -
When I load this RDF from file:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<foaf:Person>
<foaf:name>My Name</foaf:name>
</foaf:Person>
</rdf:RDF>
using this code
String fileName = "foaf.rdf";
try {
InputStream is = new FileInputStream(fileName);
Model model = Rio.parse(is, "", RDFFormat.RDFXML);
System.out.println();
Rio.write(model, System.out, RDFFormat.RDFXML);
System.out.println();
is.close();
}
catch (Exception ex) {
System.out.println(ex.toString());
}
the output looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:nodeID="node1basf0r6vx1">
<rdf:type rdf:resource="http://xmlns.com/foaf/0.1/Person"/>
<foaf:name rdf:datatype="http://www.w3.org/2001/XMLSchema#string">My Name</foaf:name>
</rdf:Description>
</rdf:RDF>
How would I go about getting RDF printed out in the original format?
RDF4J has also a pretty print function. Maybe this can help you with your output.
You just have to create a writer and then set pretty print to true.
Rio.createWriter(format, outputStream).set(BasicWriterSettings.PRETTY_PRINT, true)
I am using perl for converting an XML file JSON. I was able to write the code for converting the input XML file to Json format.
Here is the sample xml:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Person SchemaVersion="1.0.8">
<ID>0</ID>
<Home ID="ABC-XYZ" State="Unknown">
<Location>
<SiteName></SiteName>
<Number>62</Number>
<MaxSize>0</MaxSize>
<Comment></Comment>
</Location>
<Laptop>
<FileName>/usr/temp/RPM_020515_.tar.gz</FileName>
</Laptop>
</Home>
</Person>
sample perl code doing json conversion:
#!/usr/bin/perl
use JSON;
use XML::Simple;
# Create the object of XML Simple
my $xmlSimple = new XML::Simple(KeepRoot => 1);
# Load the xml file in object
my $dataXML = $xmlSimple->XMLin("input/path/to/above/XMLFILE");
# use encode json function to convert xml object in json.
my $jsonString = encode_json($dataXML);
# finally print json
print $jsonString;
Output JSON value:
{
"Person": {
"ID": "0",
"SchemaVersion": "1.0.8",
"Home": {
"ID": "ABC-XYZ",
"Laptop": {
"FileName": "/usr/temp/RPM_020515_.tar.gz"
},
"Location": {
"Number": "62",
"MaxSize": "0",
"Comment": { },
"SiteName": { }
},
"State": "Unknown"
}
}
}
Above code is working fine.
My question is and this is where i am actually stuck.
I need to do one more thing along with JSON conversion which is checking if element "FileName" in XML is empty or not. if its not extract its value as well.
So output will be two things:
1. XML To JSON convert ( working fine )
2. Along with point 1. extract the value of nested element in XML
"FileName". I need that for some business logic need in next step.
Can some perl experts help me here and suggest me how i can do that in my current perl code.
Thanks for helping in advance.
This is my first perl script so please excuse me if this is a too trivial question to ask.
Tried reading the perl docs but not that helpful.
NOTE: I am trying to use only perl built in libraries not any new third party libraries that is the reason i used XML::Simple. Its production code restriction ( very bad boundation ). I hope something for this exists in XML::Simple or JSON.
As XML::Simple docs note, it 'slurps' the XML into a data structure analogous to the input XML. Thus, to figure out the contents of the XML, just treat it as the hash reference it likely is:
if ($dataXML->{Person}{Home}{ID} eq 'foo') {
# Some action
...
}
You should use XML::LibXML instead of XML::Simple. Then use xpath to query each document. I'd take a look at the code of XML::XML2JSON to see if it can be a good fit for the problem…
I've got an XML document that I receive from a REST service that I wish to parse. The service might change their element and tag names so I'm trying to come up with some completely generic solution that saves the document structure as some kind of object with attributes.
I'm not sure how/if the C++ and Qt API's allow me to accomplish such a thing however. I've thought of creating some kind of keyed map that can hold element names as string keys and values would be their children in some recursive fashion. Being very new to Qt and C++ I'm not sure how I can accomplish this.
This could be an example XML document:
<root>
<element id="1">
<name>SomeName</name>
<desc>SomeDesc</desc>
<params>
<param pid="1">True</param>
<param pid="2">False</param>
</params>
...
<Some unknown element></Some unknown element>
</element>
</root>
This is how I convert the HTTP response (QNetworkReply) to a DOM document I can use in Qt:
QByteArray data = reply->readAll();
QDomDocument doc;
doc.setContent(data);
QDomNodeList nodes = doc.elementsByTagName("root");
if (nodes.size() > 0) {
// Prints all elements, should be able to save in a map somehow? Perhaps there is a better way?
qDebug() << nodes.at(0).toElement().text();
}
I would love some input on how I can parse this in a way that allows me to keep all information in the XML even without knowing the element, attribute and tag names. Something like this:
element = {
id : 1,
name : 'SomeName',
desc : 'SomeDesc',
params : [{
pid : 1,
param : True
}, {
pid : 2,
param : False
}
],
some unknown element : some unknown values
}
I am using XML DOM API in C++ to parse an XML file. I can't find any method to get the attribute value in a node element.
For example, in the following xml
<test>
<fruit count="10">
...
...
</fruit>
<test>
I need to get the count string("10") using XML APIs. Can anybody help me with some code snippets.
Use DOM Parser API to get attribute value count.
Refer below sample code:
//code to perform some process for parsing the input file and get rootElement
DOMNodeList* fruitNodes= rootElement->getElementsByTagName(XMLString::transcode("fruit"));
DOMNode* node = fruitNodes->item(0);
DOMElement* fruitElement = dynamic_cast <xercesc::DOMElement*>(node);
const XMLCh* attrValue = fruitElement->getAttribute(XMLString::transcode("count"));
you can get value 10 from attrValue using: string(XMLString::transcode(attrValue))
Based on http://msdn.microsoft.com/en-us/library/windows/desktop/ms754523(v=vs.85).aspx
Try something like:
pXMLDomNodeList = pXMLDocElement->selectNodes("/test/fruit/#count");