1

I was wondering if there is already a good solution for this potential frequent problem. I only want to get elements with a specific name from an xml document, e.g. <name> and get all the occurrences in the document and convert it into the json format, by keeping the individual positioning of the elements.

I currently do it by 'hand' by matching the element name and build the json format by iterating through the result tree. It makes a lot of work and I'm sure there is a solution out there for those kind of transformations. Does someone know a solution?

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
Ole
  • 161
  • 1
  • 3
  • 12
  • Well, XSLT 3 and XPath 3.1 as supported by Saxon 9.8 all editions or also earlier commercial editions have support for https://www.w3.org/TR/xpath-functions/#func-xml-to-json and there is also maps and arrays you can create and serialize with output method `json`. But you have to understand that there is not one unique representation of XML as JSON so you might need to transform your XML first and write additional code to create maps/arrays. – Martin Honnen Feb 02 '18 at 20:01
  • For instance http://xsltfiddle.liberty-development.net/3Nqn5Yc selects all `name` elements in the document and converts them into an XPath string array `array{//name/string()}` then serialized as JSON. – Martin Honnen Feb 02 '18 at 20:05
  • http://xsltfiddle.liberty-development.net/3Nqn5Yc/1 is a different way to get the same output, it transforms the `name` elements into the format for `xml-to-json` and then outputs that string result as `text`. – Martin Honnen Feb 02 '18 at 20:12
  • If you want to build a nested structure then http://xsltfiddle.liberty-development.net/3Nqn5Yc/2 has an example using `xml-to-json`. – Martin Honnen Feb 03 '18 at 07:57
  • And http://xsltfiddle.liberty-development.net/3Nqn5Yc/3 gives the same result constructing maps recursively using `apply-templates` and `xsl:map` and `xsl:map-entry` and serializing as `json`. – Martin Honnen Feb 03 '18 at 08:26
  • You really need to show us sample input, desired output, and your current code. Otherwise we're really just guessing your requirements. – Michael Kay Feb 03 '18 at 09:06

0 Answers0