How can I change the namespace on every node in a DOM?

前端 未结 8 719
小蘑菇
小蘑菇 2020-12-19 10:05

How can I, given a w3c DOM (Java\'s default implementation, specifically) change the namespace of every element/attribute/node in that DOM? Efficiently, preferably. The DO

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 10:30

    How can I, given a w3c DOM (Java's default implementation, specifically) change the namespace of every element/attribute/node in that DOM? Efficiently, preferably.

    I don't think there is an efficient solution that is also robust. You can't just rename something on the root element. Consider these documents:

    Doc1

    
    
      
        
          
        
      
    
    

    Doc2

    
    
      
        
          
        
      
    
    

    Doc3

    
    
      
        
          
        
      
    
    

    These three documents are equivalent in a namespace-aware DOM. You could run the same namespaced XPath queries against any of them.

    Since the DOM allows you to specify exactly how nodes should be namespaced, there is no catch-all, one-step call to change a namespace. You need to walk the DOM, taking into consideration not only prefix and URI values, but their scope at any given time.

    This XSLT can be used with a Transformer to change elements namespaced as urn:fleet to be namespaced as urn:new:

    
    
      
      
        
          
          
        
      
      
        
        
          
          
        
      
    
    

    Caveats: further tweaking would be required to handle namespaced attributes; dangling urn:fleet declarations can be left behind, which is messy, but largely inconsequential; probably other stuff I haven't thought of.

提交回复
热议问题