XPATH表达式匹配=" TAGNAME"匹配但匹配=" PARENT / TAGNAME"才不是

时间:2016-11-15 11:14:00

标签: xslt xpath

我是XSLT的新手,想要删除所有"私有"标签来自csproj-File中的引用,然后引入Private =" False"标签背后的每一个" HintPath"代替。我在没有完全理解我在做什么的情况下为此编写了一个有效的解决方案:

XSLT

    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:DUMMY="http://schemas.microsoft.com/developer/msbuild/2003"
        xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- use DUMMY namespace as default, would otherwise write missing ns explicitly -->
 <xsl:output encoding="UTF-8" indent="yes"/> <!-- encoding as required for output file, indent=yes: would write all text in one line otherwise -->
 <xsl:strip-space elements="*"/> <!-- delete all white spaces -->

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>

<xsl:template match="Private"/> <!-- obsolete line: without the namespace workaround: no match -->
<xsl:template match="DUMMY:Private"/> <!-- working line: only deletes tags itself, not indention -->
<xsl:template match="DUMMY:Reference/Private"/> <!-- obsolete line: Does not match! -->
<xsl:template match="DUMMY:Reference//Private"/> <!-- obsolete line: Does also not match! -->

<xsl:template match="DUMMY:HintPath">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
  <xsl:element name="Private">
    <xsl:text>False</xsl:text>
  </xsl:element>
 </xsl:template>

</xsl:stylesheet>

示例输入文件:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- The original document has an anonymous default namespace -->
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <ItemGroup>
    <Reference Include="Configuration">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>$(SolutionDir)..\..\public\Bin\$(Configuration)\Configuration.dll</HintPath>
    </Reference>
    <Reference Include="Core">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>$(SolutionDir)..\..\public\Bin\$(Configuration)\Core.dll</HintPath>
      <Private>False</Private>
    </Reference>
    <Reference Include="Data">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>$(SolutionDir)..\..\public\Bin\$(Configuration)\Data.dll</HintPath>
      <Private>True</Private>
    </Reference>
  </ItemGroup>
</Project>

如上所述:这对我有用,但到目前为止找到它是相当复杂的。有没有更好的方法来使用XSLT完成该任务?

我不喜欢这样的事实:如果&#34;私人&#34;标签出现在文档中的其他位置而不是&#34;参考&#34; s。但我没有找到指定它的方法,包括父标记。任何提示?

第二个问题:是否有更简单的方法来处理名称空间?

欢迎任何建议。

1 个答案:

答案 0 :(得分:2)

使用前缀来限定所有元素名称:<xsl:template match="DUMMY:Reference/DUMMY:Private"/>