简体   繁体   English

如何获取XSL文件目录的绝对路径?

[英]How to get an absolute path to the directory of the XSL file?

My Schema.xsd file is located in the same directory with the .xsl file. 我的Schema.xsd文件与.xsl文件位于同一目录中。 In the .xsl file I would like to generate a link to Schema.xsl in the generated output. .xsl文件中,我想在生成的输出中生成指向Schema.xsl的链接。 The generated output is located in different directories. 生成的输出位于不同的目录中。 Currently I do it like this: 目前我是这样的:

   <xsl:template match="/">
     <root version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation="../../../Schema.xsd">
     <!-- . . . -->

However this forces the generated output to be located 3 levels under the directory of Schema.xsd . 但是,这将强制生成的输出位于Schema.xsd目录下的3个级别。 I would like to generate an absolute path to the schema in the output, so the output could be located anywhere. 我想在输出中生成指向架构的绝对路径,因此输出可以位于任何地方。

Update. 更新。 I use XSLT 1.0 ( XslCompiledTransform implementation in .NET Framework 4.5). 我使用XSLT 1.0(.NET Framework 4.5中的XslCompiledTransform实现)。

XSLT 2.0 Solution XSLT 2.0解决方案

Use the XPath 2.0 function, resolve-uri() : 使用XPath 2.0函数resolve-uri()

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"
              omit-xml-declaration="yes"
              encoding="UTF-8"/>
  <xsl:template match="/">
    <root version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="{concat(resolve-uri('.'), 'Schema.xsd')}">
    </root>
  </xsl:template>

</xsl:stylesheet>

Yields, without parameter passing and regardless of the input XML: 不考虑参数传递且不考虑输入XML的收益:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      version="1.0"
      xsi:noNamespaceSchemaLocation="file:/c:/path/to/XSLT/file/Schema.xsd"/>

This is a sketch of how to do it (also see Passing parameters to XSLT Stylesheet via .NET ). 这是如何执行此操作的草图(另请参见通过.NET将参数传递给XSLT样式表 )。

In your C# code you need to define and use a parameter list: 在您的C#代码中,您需要定义和使用参数列表:

XsltArgumentList argsList = new XsltArgumentList();
argsList.AddParam("SchemaLocation","","<SOME_PATH_TO_XSD_FILE>");

XslCompiledTransform transform = new XslCompiledTransform();
transform.Load("<SOME_PATH_TO_XSLT_FILE>");

using (StreamWriter sw = new StreamWriter("<SOME_PATH_TO_OUTPUT_XML>"))
{
    transform.Transform("<SOME_PATH_TO_INPUT_XML>", argsList, sw);
} 

Your XSLT could be enhanced like this: 您的XSLT可以这样增强:

...
<xsl:param name="SchemaLocation"/> <!-- this more or less at the top of your XSLT! -->
...

<xsl:template match="/">
   <root version="1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="{$SchemaLocation}">
   ...
   ...
</xsl:template>
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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