Reputation: 53
I have an android XML file in the following format
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<!-- I AM A COMMENT -->
<!-- General -->
<string name="foo">foo</string>
<string name="bar">bar</string>
</resources>
I want my JSON output to look like this:
{
"resources": {
"foo": "foo",
"bar": "bar"
}
}
That is, I want the values of the node names to be the Keys, and the Values of the contents of the nodes to be the values in the JSON KV pairs.
is this doable with nokogiri attributes? or crack?
or must i perform pre-processing on the XML beforehand?
Upvotes: 0
Views: 125
Reputation: 664
You can use XSLT to transform the XML and then use nokogiri to transform it:
The XSLT I used:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="resources">
{
"resources": {
<xsl:for-each select="string">
"<xsl:value-of select="./@name"/>":
"<xsl:value-of select="."/>"
<xsl:choose>
<xsl:when test="position() != last()">,</xsl:when>
</xsl:choose>
</xsl:for-each>
}
}
</xsl:template>
</xsl:stylesheet>
Apply the XSLT with nokogiri:
require 'nokogiri'
document = Nokogiri::XML(File.read('input.xml'))
template = Nokogiri::XSLT(File.read('template.xslt'))
transformed_document = template.transform(document)
Upvotes: 1