如何在SVG文件替换为XML标签所有出现由它的价值

问题描述 投票:0回答:2

我如何可以通过使用XSLT模板其值替换给定的XML标签的所有匹配?

例如,<tspan x="12.02" y="0">ogen</tspan>将成为ogen

我可以删除使用此命令行中的所有事件:

xmlstarlet ed -N ns=http://www.w3.org/2000/svg -d "//ns:tspan" foo.svg

但我仍然无法找到它的价值来取代它,而不是方法。

xslt xmlstarlet
2个回答
1
投票

考虑利用XSL样式表包含必要的规则模板。例如:

strip-tag.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:template match="node()[not(name()='tspan')]|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

该模板的所有节点,并将它们复制匹配。然而,在属性XPath,(即match部分)中定义的表达[not(name()='tspan')],exludes任何tspan元素节点,并从被复制他们的相关联的属性节点(S) - 有效地删除它们。子元素节点和/或所述tspan元件的文本节点将被复制,所以根据需要,他们将保持在输出中。

source.xml

请看下面的例子source.xml文件:

<?xml version="1.0"?>
<svg width="250" height="40" viewBox="0 0 250 40" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <text x="10" y="10">The <tspan x="10" y="10">quick</tspan> brown fox <tspan x="30" y="30">jumps</tspan> over the lazy dog</text> 
  <a href="https://www.example.com"><text x="100" y="100"><tspan x="50" y="50">click</tspan> me</text></a> 
</svg>

Transforming the source xml

  • 运行以下xmlstarlet命令(与用于文件中定义的正确的路径): $ xml tr path/to/strip-tag.xsl path/to/source.xml
  • 或者运行以下命令xsltproc(如果你的系统有它可用): $ xsltproc path/to/strip-tag.xsl path/to/source.xml

将以下内容打印到控制台:

<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="250" height="40" viewBox="0 0 250 40" version="1.1">
  <text x="10" y="10">The quick brown fox jumps over the lazy dog</text>
  <a href="https://www.example.com"><text x="100" y="100">click me</text></a>
</svg>

注意:开启和关闭tspan标签的所有实例已被删除。

Removing multiple

要删除多个不同命名的元素利用在and属性中定义的XPath表达式的match运算符。例如:

<!-- strip-multiple-tags.xsl-->

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
  <xsl:template match="node()[not(name()='tspan') and not(name()='a')]|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

转化source.xml使用这个模板将导致以下的输出:

<svg xmlns="http://www.w3.org/2000/svg" width="250" height="40" viewBox="0 0 250 40" version="1.1">
  <text x="10" y="10">The quick brown fox jumps over the lazy dog</text>
  <text x="100" y="100">click me</text>
</svg>

注:这两个tspana标签的所有实例已被删除。


0
投票

这个片段会做你想要什么:

<xsl:template match="tspan">
    <xsl:value-of select="text()"/>
</xsl:template>

它发现tspan元素,并放弃其所有的内容。该xsl:value-of select="text()"声明只复制到输出的文本节点的内容。

© www.soinside.com 2019 - 2024. All rights reserved.