【问题标题】:XSLT remove unwanted xmlns from xslt resultXSLT 从 xslt 结果中删除不需要的 xmlns
【发布时间】:2014-01-22 13:08:02
【问题描述】:

我有这个包含一个 XML 作为字符串的 XML:

<Result>
    <XML>
       &lt;PingRS xmlns="http://www.test.com"&gt;
          &lt;Message&gt;
             Hello.
          &lt;/Message&gt;
      &lt;/PingRS&gt;
    </XML>
</Result>

我正在使用这个 XSLT 对其进行转换:

<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:template match="/Result">
    <xsl:value-of select="XML" disable-output-escaping="yes" />
  </xsl:template> 
</xsl:stylesheet>

要得到这个结果:

<PingRS xmlns="http://www.test.com">
    <Message>Hello.</Message>
</PingRS>

我想在同一个 XSLT 文件中删除这个 xmlns 属性。这可能吗?

【问题讨论】:

  • 你能转换两次吗(不同的样式表或相同的样式表)?

标签: xml xslt


【解决方案1】:

这是可能的,但由于&lt;XML&gt; 元素确实包含 XML,因此必须通过字符串操作来完成:

<xsl:template match="/Result">
<xsl:variable name="xmlns" select="' xmlns=&quot;http://www.test.com&quot;'" />
    <xsl:value-of select="substring-before(XML, $xmlns)" disable-output-escaping="yes" />
    <xsl:value-of select="substring-after(XML, $xmlns)" disable-output-escaping="yes" />
</xsl:template> 

顺便说一句,您显示的结果不正确-您真正得到的是:

   <PingRS xmlns="http://www.test.com">
      <Message>
         Hello.
      </Message>
  </PingRS>

编辑:

如果事先不知道xmlns的内容,可以使用:

<xsl:template match="/Result">
    <xsl:value-of select="substring-before(XML, ' xmlns=&quot;')" disable-output-escaping="yes" />
    <xsl:value-of select="substring-after(substring-after(XML, ' xmlns=&quot;'), '&quot;')" disable-output-escaping="yes" />
</xsl:template> 

【讨论】:

  • 谢谢。如果 xmlns 的内容会改变,我可以在选择中使用正则表达式吗?喜欢select="'xmlns=&amp;quot;*&amp;quot;'"
  • @bale3 您不能在 XSLT 1.0 中使用正则表达式;您只需要使用更精细的字符串操作 - 请参阅我的答案的编辑。
  • 答案是使用字符串操作。 XSLT 中的字符串操作存在与任何编程语言中使用字符串进行 XML 处理相同的弱点。 IE。 XSLT 正是在这种情况下工作,但不适用于等价的 XML,例如 &lt;Result&gt; &lt;XML&gt; &amp;lt;x:PingRS xmlns:x="http://www.test.com"&amp;gt; &amp;lt;y:Message xmlns:y="http://www.test.com"&amp;gt; Hello. &amp;lt;/y:Message&amp;gt; &amp;lt;/x:PingRS&amp;gt; &lt;/XML&gt; &lt;/Result&gt;。因此,如果您无法控制输入,则给定的解决方案可能不起作用。
  • @ThomasW。 1.给定的输入包含一个需要修改的字符串;因此需要字符串操作。 2. 一般来说,XSLT 以它设计的格式(语法、模式)工作;这不仅限于字符串。
猜你喜欢
  • 2015-11-16
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
相关资源
最近更新 更多