0

I'm converting xml to json using xslt. The problem I'm having is: if a specific xml element dosn't have siblings it is not returned as an array.

        <xsl:if test="count(preceding-sibling::*[name() = name(current())]) = 0">
        <xsl:text>"</xsl:text><xsl:value-of select="name()" /><xsl:text>":</xsl:text>
        <xsl:if test="count(following-sibling::*[name() = name(current())]) &gt; 0">
            <xsl:text>[</xsl:text>
        </xsl:if>
    </xsl:if>

What I would like is if siblings of the parent have have the same element(s) as an array then this element must also be an array.

so what I would like is:

<element>
 <child_element>
  <grandchild_element>
     only one
  </grandchild_element>
 </child_element>
 <child_element>
  <grandchild_element>
     one
  </grandchild_element>
  <grandchild_element>
     two
  </grandchild_element>
 </child_element>

I would like the following output

{
    "element": {
        "child-element": [
            {
                "grandchild_element": "only one"
            }
        ],
        "child-element": [
            {
                "grandchild_element": "one" ,
                "grandchild_element": "two"
            }
        ]
    }
}

thanks

1
  • Provide input XML and desired output. Commented Sep 12, 2011 at 12:23

1 Answer 1

2

There have been quite a few attempts to define mappings between XML and JSON, and it's not a trivial problem. I would recommend that before attempting to code this conversion, you study some of the existing proposed mappings, and if you want to do a mapping that is different, you specify it carefully before you start coding.

One of the problems you are going to hit is that it you try and do it without knowledge of the schema, you will find it very hard to know when to output a single JSON object and when to output a single-member array. For example, if someone has one phone number, you'll output a single value, but if they have several, you will output an array: you can't know when you see a single phone number whether the recipient is expecting an array of phone numbers. This isn't a coding problem, it's a problem that there's not enough information in the XML instance to make the distinction.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that, but in this case i always want specific elements to be mapped as an array. in the above example the child-element's children.
thanks, needed to get my head around it. Solution was creating an attribute in the xml that inferred an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.