Get XML node with namespace in java

前端 未结 3 1486
失恋的感觉
失恋的感觉 2021-01-21 15:43

I have the next XML:




        
3条回答
  •  花落未央
    2021-01-21 16:07

    A - Demo Code

    import java.io.File;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    public class GetXMLNodeInJavaDemo {
    
        public static void main(String[] args) {
    
            try {
                File fXmlFile = new File("sampleFile.xml");
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    
                dbFactory.setNamespaceAware(true);
    
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(fXmlFile);
    
                doc.getDocumentElement().normalize();
    
                printByElementTagname(doc);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static void printByElementTagname(Document doc) {
            NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("*", "UBLExtension");
            Node node;
            for(int i = 0; i < nodes.getLength(); i++) {
                node = nodes.item(i);
                System.out.println(node.getNodeName() + " : " + node.getTextContent().trim());
            }
        }
    
    }
    

    B - Sample File : sampleFile.xml

    
    
        
            
                
                    Some Code
                
            
            
                
                    What you want
                
            
        
    
    

    C - Sample Output

    ext:UBLExtension : Some Code
    ext:UBLExtension : What you want
    

提交回复
热议问题