c#XDocument:检查特定节点名称是否存在,如果不存在,则添加

时间:2019-02-11 10:50:58

标签: c# .net xml xslt

我有下面的节点,如果不存在,则需要在xslt中添加它:-

<xsl:template name="URLSpliter">
    <xsl:param name="url" />
    <xsl:variable name="splitURL" select="substring-after($url, '/')" />
    <xsl:if test="contains($splitURL, '/')">
      <!--To call the template recursively-->
      <xsl:call-template name="URLSpliter">
        <xsl:with-param name="url" select="$splitURL" />
      </xsl:call-template>
    </xsl:if>
    <xsl:if test="not(contains($splitURL, '/'))">
      <xsl:value-of select="$splitURL" />
    </xsl:if>
  </xsl:template>

为此,首先我需要检查它是否存在?-

我已经通过-

对其进行了检查
IEnumerable<XElement> xElements = from xmlAuthor in doc.Descendants()
                                                      let xElement = xmlAuthor.Element("URLSpliter")
                                                      where xElement != null 
                                                      select xmlAuthor;

                    var IsUrlSplitterExists= xElements.Any();

                    if(IsUrlSplitterExists)
                    {

                    }

1。我想知道它的正确方法吗?

  1. 如果不存在(元素[name =“ URLSpliter”]),则需要添加。

如何将其添加为xslt的第一个节点?

1 个答案:

答案 0 :(得分:2)

要使用LINQ to XML在XSLT名称空间中选择此类元素,您将使用

XNamespace xsl = "http://www.w3.org/1999/XSL/Transform"; 
if (!doc.Root.Elements(xsl + "template").Where(t => (string)t.Attribute("name") == "URLSplitter").Any()) { 
  doc.Root.AddFirst(new XElement(xsl + "template", new XAttribute("name", "URLSplitter"), ...)) 
}

当然,由于XSLT是XML,因此您最好使用XSLT来操纵XSLT:

<xsl:stylesheet 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:axsl="http://www.w3.org/1999/XSL/Transform-alias"
  exclude-result-prefixes="axsl"
  version="1.0">

  <xsl:namespace-alias stylesheet-prefix="axsl" result-prefix="xsl"/>

  <xsl:output indent="yes"/>

  <xsl:param name="new-template">
   <axsl:template name="URLSpliter">
    <axsl:param name="url" />
    <axsl:variable name="splitURL" select="substring-after($url, '/')" />
    <axsl:if test="contains($splitURL, '/')">
      <!--To call the template recursively-->
      <axsl:call-template name="URLSpliter">
        <axsl:with-param name="url" select="$splitURL" />
      </axsl:call-template>
    </axsl:if>
    <axsl:if test="not(contains($splitURL, '/'))">
      <axsl:value-of select="$splitURL" />
    </axsl:if>
  </axsl:template>
 </xsl:param>

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

  <xsl:template match="xsl:transform[not(xsl:template[@name = 'URLSplitter'])] | xsl:stylesheet[not(xsl:template[@name = 'URLSplitter'])]">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:copy-of select="$new-template"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/94rmq5T

相关问题