XPath to return default value if node not present

后端 未结 5 1908
无人及你
无人及你 2020-12-05 05:53

Say I have a pair of XML documents


    
    mystring

and



        
5条回答
  •  囚心锁ツ
    2020-12-05 06:05

    @Alejandro provided the best XPath 1.0 answer, which has been known for years, since first used by Jeni Tennison almost ten years ago.

    The only problem with this expression is its shiny elegance, which makes it difficult to understand by not only novice programmers.

    In a hosted XPath 1.0 (and every XPath is hosted!) one can use more understandable expressions:

    string((/Foo/Baz | $vDefaults[not(/Foo/Baz/text())]/Foo/Baz)[last())
    

    Here the variable $vDefaults is a separate document that has the same structure as the primary XML document, and whose text nodes contain default values.

    Or, if XSLT is the hosting language, one can use the document() function:

    
     
    
     
        
            
            not-found
      
     
    
     
         
     
    
    

    Or, not using concat():

    
     
    
     
        
            
            not-found
      
     
    
     
    
     
         
     
    
    

提交回复
热议问题