简体   繁体   English

如何检查xml中是否存在标签

[英]how to check if tag is present in xml or not

my XML is - 我的XML是-

<app>
 <data>
    <lang>en</lang>
 </data>
</app>

I want to check, whether 'lang' tag/element is present or not. 我想检查“ lang”标记/元素是否存在。 I am using below code to check it, but I think it is not working. 我正在使用下面的代码进行检查,但我认为它不起作用。 - --

<xsl:if test="app/data/lang">
<xsl:call-template name="xyz" /></xsl:if>

I am not able to understand what I am doing wrong here. 我无法理解我在这里做错了什么。 I referred this page of stackoverflow. 我提到了stackoverflow的这一页。 Please suggest any other way do solve this. 请提出其他解决方法。 Thanks in advance! 提前致谢!

Answer - 答案-

After doing many changes I got one solution. 经过许多更改后,我得到了一个解决方案。 I made a small change to solve this issue. 我做了一个小小的改动来解决这个问题。 I added '/' before 'app'. 我在“ app”之前添加了“ /”。

<xsl:if test="/app/data/lang">
  <xsl:call-template name="xyz" />
</xsl:if>

Thanks everyone for sharing their solutions. 感谢大家分享他们的解决方案。

You can use XSLT checking . 您可以使用XSLT检查。 Choose and When is good for doing it Below is the sample code 选择并在什么时候适合这样做下面是示例代码

   <xsl:choose>
          <xsl:when test="app/data/lang">
                 *write what ever you want*
          </xsl:when>
   </xsl:choose>

Eg in a template matching app you can use <xsl:if test="data/lang"> . 例如,在模板匹配app您可以使用<xsl:if test="data/lang">

The tag mentioned must exist, although it may be empty. 提及的标签必须存在,尽管它可以为空。

A suspected reason that your script failed is that the current object may be such that app/data/lang path finds nothing. 您的脚本失败的一个可疑原因是当前对象可能是app/data/lang路径找不到任何对象。

For a working example see http://xsltransform.net/bEJaog9 有关工作示例,请参见http://xsltransform.net/bEJaog9

To get the "Absent" case, change eg the name of source lang tag to any other. 要获得“不存在”的情况,请将源lang标记的名称更改为其他名称。

Based on my understanding giving this answer, consider this might be your XML 根据我对给出此答案的理解,认为这可能是您的XML

<Data>
    <Record>
     <AddInfo>
     </AddInfo>
    </Record>
</Data>

you need to check AddInfo tag based on you have to call-template, then this would be the XSL need to form 您需要根据需要调用模板检查AddInfo标记,那么这将是XSL需要形成的形式

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>

  <xsl:template match="Data/Record">
      <xsl:choose>
        <xsl:when test="AddInfo">Present</xsl:when>
        <xsl:otherwise>Not Present</xsl:otherwise>
      </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Based on present or not present, you provide your condition. 根据存在或不存在,您提供您的条件。 More stuff related to call-template Link here 与呼叫模板相关的更多信息

I made a small change to solve this. 我做了一个小小的改动来解决这个问题。 I added '/' before 'app'. 我在“ app”之前添加了“ /”。

<xsl:if test="/app/data/lang">
  <xsl:call-template name="xyz" />
</xsl:if>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM