【问题标题】:How to get an absolute path to the directory of the XSL file?如何获取 XSL 文件目录的绝对路径?
【发布时间】:2014-09-15 04:13:32
【问题描述】:

我的Schema.xsd 文件与.xsl 文件位于同一目录中。在.xsl 文件中,我想在生成的输出中生成指向Schema.xsl 的链接。生成的输出位于不同的目录中。目前我是这样做的:

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

但是,这会强制生成的输出位于Schema.xsd 目录下的 3 个级别。我想在输出中生成模式的绝对路径,因此输出可以位于任何地方。

更新。我使用 XSLT 1.0(XslCompiledTransform 在 .NET Framework 4.5 中实现)。

【问题讨论】:

  • 为什么不将 XSL 文件的目录作为参数传递给 XSLT 进程?
  • @MarcusRickert,谢谢你的提示。我是 XSLT 的新手。我将不得不研究是否可以在 C# 中使用 XslCompiledTransform,因为我以这种方式运行 xsl 文件。
  • 这在C#中应该是可能的。

标签: c# xml xslt xsd filepath


【解决方案1】:

XSLT 2.0 解决方案

使用 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>

产量,无需参数传递,无论输入 XML:

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

【讨论】:

  • +1。我使用 XSLT 1.0,但是这个答案可能对其他在 2.0 中遇到类似问题的人有用。或者我可以稍后切换到 2.0。
【解决方案2】:

这是一个如何做的草图(另见Passing parameters to XSLT Stylesheet via .NET)。

在您的 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);
} 

您的 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>
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多