문제

값이 null이거나 비어 있는지 어떻게 확인할 수 있습니까? XSL?

예를 들어, categoryName 비었다?나는 선택할 때 건설하다.

예를 들어:

<xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>
도움이 되었습니까?

해결책

test="categoryName != ''"

편집하다: 이것은 내 의견으로는 의사 코드와 XSLT에 대한 나의 초기 경험을 포함하여 질문에서 유추 된대로 [not] null 또는 empty"에 대한 가장 가능성이 높은 해석을 다룹니다. 즉, "다음 Java와 동등한 것은 무엇입니까?":

!(categoryName == null || categoryName.equals(""))

자세한 내용은 Null 대 비어있는 것을 뚜렷하게 식별하십시오. 아래의 Johnvey의 답변 및/또는 XSLT '바이올린' Michael Kay의 의견과 여섯 번째 가능한 해석의 옵션이 포함 된 답변에서 조정했습니다.

다른 팁

다른 정보가 없으면 다음 XML을 가정하겠습니다.

<group>
    <item>
        <id>item 1</id>
        <CategoryName>blue</CategoryName>
    </item>
    <item>
        <id>item 2</id>
        <CategoryName></CategoryName>
    </item>
    <item>
        <id>item 3</id>
    </item>
    ...
</group>

샘플 사용 사례는 다음과 같습니다.

<xsl:for-each select="/group/item">
    <xsl:if test="CategoryName">
        <!-- will be instantiated for item #1 and item #2 -->
    </xsl:if>
    <xsl:if test="not(CategoryName)">
        <!-- will be instantiated for item #3 -->
    </xsl:if>
    <xsl:if test="CategoryName != ''">
        <!-- will be instantiated for item #1 -->
    </xsl:if>
    <xsl:if test="CategoryName = ''">
        <!-- will be instantiated for item #2 -->
    </xsl:if>
</xsl:for-each>

에서 빈 요소:

특정 노드의 값이 비어 있는지 테스트하려면

그것은 당신이 비어 있다는 의미에 달려 있습니다.

  • 하위 노드가 포함되어 있지 않습니다. not(node())
  • 텍스트 내용이 포함되어 있지 않습니다. not(string(.))
  • 공백 이외의 텍스트가 포함되어 있지 않습니다. not(normalize-space(.))
  • 의견을 제외하고는 아무것도 포함하지 않습니다. not(node()[not(self::comment())])

는 어때?

test="not(normalize-space(categoryName)='')"

첫 번째는 NULL 값을 다루고 두 번째는 빈 문자열과 거래합니다.

<xsl:if test="USER/FIRSTNAME">
    USERNAME is not null
</xsl:if>
<xsl:if test="not(USER/FIRSTNAME)">
    USERNAME is null
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME=''">
     USERNAME is empty string
 </xsl:if>
 <xsl:if test="USER/FIRSTNAME!=''">
     USERNAME is not empty string
 </xsl:if>

경우에 따라 값이 구체적으로 Null인지 알고 싶을 수도 있습니다. 이는 .NET 객체에서 직렬화 된 XML을 사용할 때 특히 필요합니다. 허용 된 답변은 이에 대해 작동하지만 문자열이 비어 있거나 비어있을 때 동일한 결과를 반환합니다. 즉, 구별 할 수 없습니다.

<group>
    <item>
        <id>item 1</id>
        <CategoryName xsi:nil="true" />
    </item>
</group>

따라서 속성을 간단히 테스트 할 수 있습니다.

<xsl:if test="CategoryName/@xsi:nil='true'">
   Hello World.
</xsl:if>

때로는 정확한 상태를 알아야하며 JavaScript와 달리 CategoryName이 인스턴스화되는지 간단히 확인할 수 없습니다.

<xsl:if test="CategoryName">
   Hello World.
</xsl:if>

Null 요소에 대해 True를 반환합니다.

XML에 요소가 존재하지 않을 가능성이 있다면 요소가 존재하고 문자열 길이가 0보다 크다는 것을 모두 테스트합니다.

<xsl:choose>
    <xsl:when test="categoryName and string-length(categoryName) &gt; 0">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

이 질문이 오래되었다는 것을 알고 있지만 모든 답변 중에서 XSLT 개발에서 이 사용 사례에 대한 일반적인 접근 방식이 누락되었습니다.

OP에서 누락된 코드가 다음과 같다고 상상합니다.

<xsl:template match="category">
    <xsl:choose>
        <xsl:when test="categoryName !=null">
            <xsl:value-of select="categoryName " />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="other" />
        </xsl:otherwise>
    </xsl:choose>
</category>

입력은 다음과 같습니다.

<categories>
    <category>
       <categoryName>Books</categoryName>
    </category>
    <category>
       <categoryName>Magazines</categoryName>
       <categoryName>Periodicals</categoryName>
       <categoryName>Journals</categoryName>
    </category>
    <category>
        <categoryName><!-- please fill in category --></categoryName>
    </category>
    <category>
        <categoryName />
    </category>
    <category />
</categories>

즉, 0, 비어 있음, 단일 또는 다중이 있을 수 있다고 가정합니다. categoryName 강요.이 모든 경우를 처리하려면 다음을 사용하십시오. xsl:choose-style 구성, 즉 명령형은 빠르게 지저분해집니다(요소가 다른 수준에 있을 수 있는 경우 더욱 그렇습니다!).XSLT의 일반적인 프로그래밍 관용구는 템플릿(따라서 XSLT의 T)을 사용하는 것입니다. 이는 필수가 아닌 선언적 프로그래밍입니다(프로세서에 수행할 작업을 지시하지 않고 특정 조건이 충족되면 원하는 출력을 지시하기만 하면 됩니다).이 사용 사례의 경우 다음과 같을 수 있습니다.

<!-- positive test, any category with a valid categoryName -->
<xsl:template match="category[categoryName[text()]]">
    <xsl:apply-templates />
</xsl:template>

<!-- any other category (without categoryName, "null", with comments etc) -->
<xsl:template match="category">
    <xsl:text>Category: Other</xsl:text>
</xsl:template>

<!-- matching the categoryName itself for easy handling of multiple names -->
<xsl:template match="categoryName">
    <xsl:text>Category: </xsl:text>
    <xsl:value-of select="." />
</xsl:template>

위의 첫 번째 항목이 더 높은 우선 순위를 갖기 때문에(모든 XSLT 버전에서) 작동합니다(술어가 있음).두 번째 템플릿인 "fall-through" 일치 템플릿은 유효하지 않은 모든 것을 포착합니다.그런 다음 세 번째는 출력을 처리합니다. categoryName 올바른 방식으로 가치를 평가합니다.

이 시나리오에서는 특별히 일치할 필요가 없습니다. categories 또는 category, 달리 지정하지 않는 한 프로세서는 자동으로 모든 하위 항목을 처리하기 때문입니다(이 예에서는 두 번째와 세 번째 템플릿은 하위 항목이 없기 때문에 더 이상 하위 항목을 처리하지 않습니다). xsl:apply-templates 그 안에).

이 접근 방식은 여러 범주를 자동으로 처리하고 일치하는 다른 템플릿을 추가하여 다른 요소나 예외에 대해 확장할 수 있기 때문에 명령형 접근 방식보다 더 쉽게 확장 가능합니다. if 분기 없는 프로그래밍.

메모:그런 건 없어 null XML로.있다 xsi:nil, 그러나 이는 거의 사용되지 않으며, 특히 일종의 스키마가 없는 형식화되지 않은 시나리오에서는 거의 사용되지 않습니다.

값이 XSL로 값이 널 또는 비어 있는지 확인하려면 어떻게해야합니까?

예를 들어, if categoryName 비었다?

이것은 아마도 가장 간단한 Xpath 표현 일 것입니다 (수락 된 답변은 반대에 대한 테스트를 제공하며, 부정하면 더 길어질 것입니다) :

not(string(categoryName))

설명:

에 대한 논쟁 not() 위의 기능은입니다 false() 아니오가있을 때 정확히 categoryName 컨텍스트 항목의 Child ( "null") 또는 (단일 that) categoryName 자식은 문자열 값 - 빈 문자열입니다.

나는 a를 사용하고있다 선택할 때 건설하다.

예를 들어:

<xsl:choose>
    <xsl:when test="categoryName !=null">
        <xsl:value-of select="categoryName " />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

XSLT 2.0에서 사용하십시오:

<xsl:copy-of select="concat(categoryName,  $vOther[not(string(current()/categoryName))])"/>

다음은 완전한 예입니다:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vOther" select="'Other'"/>

 <xsl:template match="/">
  <xsl:copy-of select="concat(categoryName,$vOther[not(string(current()/categoryName))])"/>
 </xsl:template>
</xsl:stylesheet>

이 변환이 다음 XML 문서에 적용될 때 :

<categoryName>X</categoryName>

원하는 정확한 결과가 생성됩니다:

X

이 XML 문서에 적용될 때:

<categoryName></categoryName>

또는 이것에 :

<categoryName/>

또는 이것에

<somethingElse>Y</somethingElse>

올바른 결과가 생성됩니다:

Other

마찬가지로 이것을 사용하십시오 XSLT 1.0 변환:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:variable name="vOther" select="'Other'"/>

  <xsl:template match="/">
    <xsl:copy-of select=
    "concat(categoryName,  substring($vOther, 1 div not(string(categoryName))))"/>
  </xsl:template>
</xsl:stylesheet>

주목하십시오: 조건부는 전혀 사용되지 않습니다. 이 멋진 복수상 과정에서 조건부 구성을 피하는 것의 중요성에 대해 자세히 알아보십시오.

".NET의 전술 설계 패턴 : 제어 흐름"

노드에 xpath 아래와 같이 입력 XML에서 사용 가능한 값이없는 경우

<node>
    <ErrorCode/>
</node>

String () 함수는 빈 값으로 변환됩니다. 그래서 이것은 잘 작동합니다.

string(/Node/ErrorCode) =''

이와 같은 것이 나에게 효과적입니다.

<xsl:choose>
  <xsl:when test="string(number(categoryName)) = 'NaN'"> - </xsl:when> 
  <xsl:otherwise> 
    <xsl:number value="categoryName" />
  </xsl:otherwise>
</xsl:choose>

또는 다른 방법 :

<xsl:choose>
  <xsl:when test="string(number(categoryName)) != 'NaN'">
    <xsl:number value="categoryName" />
  </xsl:when> 
  <xsl:otherwise> - </xsl:otherwise>
</xsl:choose>

참고 : NULL 값을 확인하지 않거나 NULL 값을 처리하지 않으면 IE7은 NAN 대신 -2147483648을 반환합니다.

필드가 여러 번 필드가 무효가 아니기 때문에 실제로 스트링 길이를 테스트하는 것이 더 좋았습니다.

u003Cxsl:when test="string-length(field-you-want-to-test)u003C1">

내 경험에 의해 가장 좋은 방법은 다음과 같습니다.

<xsl:when test="not(string(categoryName))">
    <xsl:value-of select="other" />
</xsl:when>
<otherwise>
    <xsl:value-of select="categoryName" />
</otherwise>

간단한 카테고리 나임/텍스트 ()를 사용 하여이 테스트는 잘 작동합니다. <categoryName/> 그리고 또한 <categoryName></categoryName>.

<xsl:choose>
    <xsl:when test="categoryName/text()">
        <xsl:value-of select="categoryName" />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top