XSLT indent not working with MSXML

女生的网名这么多〃 提交于 2019-12-24 04:05:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!