xml - 判断XML标签是否包含元素的条件语句?(XSLT)
问题描述
我在下面有两个不同的 XML 文档:
XML 1
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Match>
<Trades>
<Trade fruitId="apples"/>
</Trades>
</Match>
XML 2
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Match2>
<Properties>
<foobar>123</foobar>
</Properties>
<Trades>
<Trade vegetableId="eggplant"/>
</Trades>
</Match2>
我想创建一个 XSLT 文档,该文档基本上采用 fruitId
, 或中的值vegetableId
,具体取决于哪个可用。XSLT 应该同时满足 XML1 和 XML2。
我不知道如何处理这个问题,我是否应该创建一个 if 语句来检查这个 Trades 标签是否包含一个vegetedId 或FruitId。我有点迷失在这里。这是我到目前为止想出的。
我的 XSLT 尝试
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="Trades/Trade">
<xsl: if test = "(contains(@fruitId, 'somevalue'))">
<xsl:value-of select="@fruitId"/>
</xsl:if>
<xsl: if test = "(contains(@vegetableId, 'somevalue'))">
<xsl:value-of select="@vegetableId"/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
我知道我的 contains 语句内部有“somevalue”,这不是我正在运行的实际代码,而是我想尝试的想法,尽管我不知道如何处理。
此外, <Match>
不同于<Match2>
.
请指教。谢谢!
解决方案
You could simply use something like this. Depending on the document you are passing to the transformation, only one element of the concat() function will be non-empty, so effectively only one value will be present in the output.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*" />
<xsl:template match="Trades/Trade">
<output><xsl:value-of select="concat(@fruitId,@vegetableId)"/></output>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
See it working here (I merged the two files together to test): https://xsltfiddle.liberty-development.net/ei5R4up
推荐阅读
- python - TypeError: unhashable type: 'list' pandas python
- css - 在 Emotion 中使用 `css` 属性覆盖样式组件
- c++ - 错误:在第 6 行的 '{' 标记之前不允许函数定义
- python - 我安装了诅咒,但仍然得到没有找到诅咒的错误
- javascript - Vue 组件部分工作并且没有出现在 Vue 检查器中
- google-cloud-platform - 创建 GCP Dataproc 集群时出错:“compute.projects.get”的权限被拒绝
- javascript - 一页中的多个表单-reactjs
- reactjs - Axios 内部状态未针对 React Hooks 进行更新
- python - 在 Python 3 中将双循环转换为双列表理解?
- angular - Angular 8 - 应用程序启动时未发现模块