简体   繁体   中英

How to access the content of simple type XML element via XSLT/XPath after transforming it to JSON and back to XML?

I have a XML string

<Frequency unit="Hz">200</Frequency>

which is transformed to this JSON string

{"Frequency":{"unit":"Hz","content":200}}

by using this code:

final String originalXml = "<Frequency unit=\"Hz\">200</Frequency>";
final String jsonString = XML.toJSONObject( originalXml ).toString();

Once I transform it back with this code

final String xml = XML.toString( new JSONObject( jsonString ) );

I get the resulting xml like this:

<Frequency>
   <unit>Hz</unit>
   200
</Frequency>

The question now is: How can I access the value '200' via XPath using a XSLT transformation? The goal is, to get "200 Hz" out of the XML.

Currently I'm achieving this as follows: I'm getting the whole content which returns "Hz200". Then I'm getting the content of "unit" and do a substring-after, which is quiet ugly:

<xsl:variable name="frequencyUnit" select="/Frequency/unit"/>
<xsl:value-of select="concat(substring-after(/Frequency, $frequencyUnit),' ',$frequencyUnit )"/>

With that I get the expected result "200 Hz".

I would appreciate any recommendations. Thanks in advance!

The goal is, to get "200 Hz" out of the XML.

How about:

<xsl:value-of select="normalize-space(/Frequency/text())"/>
<xsl:text> </xsl:text>
<xsl:value-of select="/Frequency/unit"/>

Or, if you prefer:

<xsl:value-of select="concat(normalize-space(/Frequency/text()), ' ', /Frequency/unit)"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM