问题
I am trying to "pretty" an XML file. As suggested in some other SO questions, I am using the following stylesheet to transform:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml" encoding="UTF-16" />
<xsl:strip-space elements="*"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
However this is not producing the desired results. For an input file of:
<A><B><C /></B></A>
the generated output is:
<?xml version="1.0" encoding="UTF-16"?>
<A>
<B>
<C>
</C>
</B>
</A>
But the output I am expecting is (header line doesn't matter):
<A>
<B>
<C />
</B>
</A>
So there are two problems:
- There is no indentation in the output
- The
<C />
tag has been "unpacked", which I don't want.
I have tried with MSXSL.exe , and by using (via C++) IXMLDOMDocument2::transformNode outputting to a BSTR
, both methods produce identical output.
What's going wrong here?
回答1:
The following WSH (Windows Scripting Host) JScript program using MSXML 6.0 (which is available on all supported Microsoft OS by default, without any installation) outputs
<?xml version="1.0" encoding="UTF-16"?>
<A>
<B>
<C></C>
</B>
</A>
Program is
var msxmlVersion = '6.0';
var xml = new ActiveXObject('Msxml2.DOMDocument.' + msxmlVersion);
xml.async = false;
xml.load('test2015012501.xml');
var xsl = new ActiveXObject('Msxml2.DOMDocument.' + msxmlVersion);
xsl.async = false;
xsl.load('test2015012501.xsl');
var resultDoc = new ActiveXObject('Msxml2.DOMDocument.' + msxmlVersion);
xml.transformNodeToObject(xsl, resultDoc);
WScript.Echo(resultDoc.xml);
the input and XSLT are your samples. So using MSXML 6.0 and transformNodeToObject you get better indentation results, although for my needs the indentation is using too many indent characters.
Of course instead of using JScript you should be able to use MSXML 6 with C++ and get the same results.
And if you want a file instead of a string you can of course use resultDoc.save('file.xml')
.
来源:https://stackoverflow.com/questions/28133229/xslt-indent-not-working-with-msxml