Remove namespace from XML in Java

前端 未结 2 426
不思量自难忘°
不思量自难忘° 2021-01-05 05:55

I want to remove namespace from XML in Java. Can you pls guide on what needs to be done. Can use DOM parser but that would be a node by node parsing. I want to know if there

2条回答
  •  情话喂你
    2021-01-05 06:35

    You can use xslt for that. Try

    removeNs.xslt

    
    
        
    
        
            
                
            
        
        
            
          
        
        
    
    

    Sample.java

    import java.io.File;
    
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.stream.StreamSource;
    
    public class Sample {
    
        public static void main(String[] args) {
            try{
                TransformerFactory factory = TransformerFactory.newInstance();
            Source xslt = new StreamSource(new File("removeNs.xslt"));
            Transformer transformer = factory.newTransformer(xslt);
    
            Source text = new StreamSource(new File("data.xml"));
            transformer.transform(text, new StreamResult(new File("output.xml")));
            System.out.println("Done");
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            }
        }
    
    }
    

提交回复
热议问题