XSLT 1.0 to move namespace to child node

前端 未结 1 1386
清歌不尽
清歌不尽 2021-01-27 11:12

I only have access to xpath 1.0 commands and functions. I need to move the namespace declaration from the root node to a child node where that namespace starts to be used.

1条回答
  •  离开以前
    2021-01-27 11:28

    Here's one way to do it.

    When this XSLT:

    
    
      
      
    
      
        
          
        
      
    
      
         
           
         
      
    
    
    

    ...is applied against the provided XML:

    
    
      10113146
      test1
      test2
      
        10113146
        120051520
      
    
    

    ...the wanted result is produced:

    
    
      10113146
      test1
      test2
      
        10113146
        120051520
      
    
    

    Explanation:

    The explanation behind why this works starts with a section from the Namespaces in XML 1.0 spec:

    The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag, excluding the scope of any inner declarations with the same NSAttName part. In the case of an empty tag, the scope is the tag itself.

    Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration.

    In a nutshell, this means that when a namespace is declared on an element, it is, in effect, defined for use on all elements underneath that original scope. Additionally, should a namespace be used on an element without first being defined elsewhere, the appropriate definition occurs on that element.

    So, using your document and my XSLT, let's see how this plays out:

    1. The first template - The Identity Template - copies all nodes and attributes as-is from the source XML to the result XML.
    2. The second template replaces the original element with a new one; incidentally, this new element does not define the http:example.com/test1 namespace. Finally, this template applies templates to all child elements of .
    3. When the processor reaches , it sees a namespace that, although present in the original XML, has not been properly defined in the result document. As such, this definition is added to .

    0 讨论(0)
提交回复
热议问题