我试图通过设置全局参数在通过 XSLT(使用 Saxon-HE v9.7.0.14)生成的 xml 文件中设置密码。
密码可以包含任何字符,因此需要将其放在CDATA
部分。
我试图通过设置来实现这一点cdata-section-elements
我的 xslt 的属性xsl:output
包含密码元素名称的元素:
<xsl:output method="xml" indent="yes" cdata-section-elements="password"/>
这是行不通的。我在下面提供了示例代码、输入、xslt、当前输出和所需输出。
我需要更改什么才能获取密码CDATA
部分?
Program:
using System;
using System.IO;
using Saxon.Api;
namespace XsltTest {
class Program {
static void Main(string[] args) {
var xslt = new FileInfo(@"transform.xslt");
var input = new FileInfo(@"input.xml");
var output = new FileInfo(@"output.xml");
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(xslt.FullName));
var transformer = executable.Load();
var destination = new DomDestination();
using (var inputStream = input.OpenRead()) {
transformer.SetInputStream(inputStream, new Uri(Path.GetTempPath()));
transformer.SetParameter(
new QName("password"),
new XdmAtomicValue("secret"));
transformer.Run(destination);
}
destination.XmlDocument.Save(output.FullName);
}
}
}
变换.xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes" cdata-section-elements="password"/>
<xsl:param name="password" />
<xsl:template match="@* | node()">
<bar>
<username>
<xsl:value-of select="//username"/>
</username>
<password>
<xsl:value-of select="$password"/>
</password>
</bar>
</xsl:template>
</xsl:stylesheet>
输入.xml:
<?xml version="1.0" encoding="utf-8" ?>
<foo>
<username>john</username>
</foo>
输出.xml:
<bar>
<username>john</username>
<password>secret</password>
</bar>
密码未放入CDATA
部分。
期望的结果:
<bar>
<username>john</username>
<password><![CDATA[secret]]></password>
</bar>