XSLT: How to convert XML Node to String

2019-01-05 04:52发布

<ROOT>
   <A>
      <B>TESTING</B>
   </A>
</ROOT>

XSL:

<xsl:variable name="nodestring" select="//A"/>
<xsl:value-of select="$nodestring"/>

I am trying to convert XML nodeset to string using XSL. Any thoughts?

10条回答
Evening l夕情丶
2楼-- · 2019-01-05 04:56

In XSLT Version 3.0. See http://myxsl.net/xslcompiledtransform/extensions/w3c.xpath.xsl#fn-serialize. This worked for me using SaxonPE.

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
<xsl:variable name="output">
    <output:serialization-parameters name="output">
        <output:method value="html"/>
    </output:serialization-parameters>
</xsl:variable>
    <xsl:template match="div">
        <xsl:value-of select="serialize(., $output/output:serialization-parameters)" />
    </xsl:template>
</xsl:stylesheet>
查看更多
趁早两清
3楼-- · 2019-01-05 04:57

Search for "XML pretty-printer". Or just have a look at the XSLT code of my XPath Visualizer (though it produces XML representation to be displayed in a browser, but you'll get the idea).

查看更多
不美不萌又怎样
4楼-- · 2019-01-05 04:57

My solution is for Saxon HE, and have this advantages:

  • it doesn't require licensing
  • supports namespaces, CDATA, escaping of special characters and many advanced XML features.

I've tried successfully with Saxon HE 9.5.X.

It is about registering a custom extension function with these contents:

import java.io.StringWriter;   
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.lib.ExtensionFunctionCall;
import net.sf.saxon.lib.ExtensionFunctionDefinition;
import net.sf.saxon.om.Sequence;
import net.sf.saxon.om.StructuredQName;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmValue;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.value.SequenceType;
import net.sf.saxon.value.StringValue;

@SuppressWarnings("serial")
public class XmlSerializer extends ExtensionFunctionDefinition {
    @Override
    public StructuredQName getFunctionQName() {
        return new StructuredQName("vis", "my.custom.uri", "serialize-xml");
    }

    @Override
    public SequenceType[] getArgumentTypes() {
        return new SequenceType[] { SequenceType.SINGLE_NODE };
    }

    @Override
    public SequenceType getResultType(SequenceType[] sequenceTypes) {
        return SequenceType.SINGLE_STRING;
    }

    @Override
    public ExtensionFunctionCall makeCallExpression() {
        return new ExtensionFunctionCall() {
            @Override
            public Sequence call(XPathContext ctx, Sequence[] secs) throws XPathException {
                StringWriter escr = new StringWriter();
                try {
                    if (secs.length == 0) {
                        throw new XPathException("Missing argument");
                    } else {
                        Serializer serializer = new Processor(ctx.getConfiguration()).newSerializer(escr);
                        serializador.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
                        serializer.serializeXdmValue(XdmValue.wrap(secs[0]));
                    }
                    return new StringValue(escr.toString());
                } catch (SaxonApiException ex) {
                    throw new XPathException("Error when invoking serialize-xml()", ex);
                }
            }
        };
    }
}

You can use this function as follows:

<xs:value-of xmlns:vis="my.custom.uri" select="vis:serialize-xml(someNode)"/>

The inverse process is documented here.

查看更多
戒情不戒烟
5楼-- · 2019-01-05 04:59
<xsl:template match="A">
  <xsl:variable name="nodes" select="." />
  <xsl:copy-of select="$nodes"/>
</xsl:template>

Updated based on comments..

OK I've never done exactly what you need before, so take this with that grain of salt (I'm winging it). Basically you need to be very concerned about 2 things: characters that require escaping and white space. In this case, the string that empo gave you in the comments above is more what you're after. Below is one way that you can make your XSL output that:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="A">

  <input type="hidden" name="hiddenxml">
    <xsl:attribute name="value">
      <xsl:apply-templates select="." mode="id" />
    </xsl:attribute>
  </input>

</xsl:template>

<xsl:template match="*" mode="id" >
  <xsl:text>&lt;</xsl:text><xsl:value-of select="name(.)" /><xsl:text>&gt;</xsl:text>
  <xsl:apply-templates select="./*" mode="id" />
  <xsl:value-of select="normalize-space(.)" />
  <xsl:text>&lt;/</xsl:text><xsl:value-of select="name(.)" /><xsl:text>&gt;</xsl:text>
</xsl:template>

</xsl:stylesheet>

You still need to be concerned with other characters that require escaping like " ' & I believe you can use translate or replace for those

查看更多
放荡不羁爱自由
6楼-- · 2019-01-05 05:09

Based on @jelovirt solution, here is a more complete piece of code:

<xsl:template match="*" mode="serialize">
    <xsl:text>&lt;</xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:apply-templates select="@*" mode="serialize" />
    <xsl:choose>
        <xsl:when test="node()">
            <xsl:text>&gt;</xsl:text>
            <xsl:apply-templates mode="serialize" />
            <xsl:text>&lt;/</xsl:text>
            <xsl:value-of select="name()"/>
            <xsl:text>&gt;</xsl:text>
        </xsl:when>
        <xsl:otherwise>
            <xsl:text> /&gt;</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template match="@*" mode="serialize">
    <xsl:text> </xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:text>="</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>"</xsl:text>
</xsl:template>

<xsl:template match="text()" mode="serialize">
    <xsl:value-of select="."/>
</xsl:template>
查看更多
Emotional °昔
7楼-- · 2019-01-05 05:09

My solution:

<xsl:template name="serializeNodeToString">
    <xsl:param name="node" />
    <xsl:variable name="name" select="name($node)" />

    <xsl:text>&lt;</xsl:text>
    <xsl:value-of select="$name" />
    <xsl:for-each select="$node/@*">
        <xsl:text> </xsl:text>
        <xsl:value-of select="name()" /><xsl:text>=&quot;</xsl:text>
            <xsl:value-of select="." /> 
        <xsl:text>&quot;</xsl:text>
        <xsl:text> </xsl:text>
    </xsl:for-each>
    <xsl:text>&gt;</xsl:text>
    <xsl:value-of select="./text()" />
    <xsl:for-each select="$node/*">
        <xsl:call-template name="serializeNodeToString">
            <xsl:with-param name="node" select="."/>
        </xsl:call-template>
    </xsl:for-each>

    <xsl:text>&lt;/</xsl:text>
    <xsl:value-of select="$name" />
    <xsl:text>&gt;</xsl:text>
</xsl:template>
查看更多
登录 后发表回答