Unable to read xml with namespace prefix using DOM parser

后端 未结 4 1820
旧巷少年郎
旧巷少年郎 2020-12-19 05:04

This is the input XML:


   
   

        
相关标签:
4条回答
  • 2020-12-19 05:32

    The W3C dom method for namespaced elements:

    getElementsByTagNameNS
    
    NodeList getElementsByTagNameNS(String namespaceURI,
                                    String localName)
    
        Returns a NodeList of all the Elements with a given local name and namespace URI in document order.
    
        Parameters:
            namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
            localName - The local name of the elements to match on. The special value "*" matches all local names. 
        Returns:
            A new NodeList object containing all the matched Elements.
        Since:
            DOM Level 2
    

    IIRC earlier version of the W3C DOM had poor support for namespaces so I don't use it. However if you use the above with the full namespaceURI http://schemas.xmlsoap.org/soap/envelope/ it should work. The prefix is unimportant - it has no permanency outside the document it is used in.

    so try:

    System.out.println("Element :" + doc.getElementsByTagNameNS(
            "http://schemas.xmlsoap.org/soap/envelope/", "Token").item(0));
    
    0 讨论(0)
  • 2020-12-19 05:35

    get the namespace first

    docFactory.setNamespaceAware(true);
    StringBuilder nameSpace = new StringBuilder(
                        doc.getDocumentElement().getPrefix() != null ? doc.getDocumentElement().getPrefix() + ":" : "");
    

    then use nameSpace variable accrodingly

    eg:

    Node node= doc.getElementsByTagName(nameSpace + "Node1").item(0)
                        .getFirstChild();
    
    0 讨论(0)
  • 2020-12-19 05:40

    You could always assign the namespace to a variable, this would allow changing it on the fly in the future.

    0 讨论(0)
  • 2020-12-19 05:40

    Try to use XPath expression. See sample code below.

    Document doc = dBuilder.parse(new ByteArrayInputStream(responseXML.getBytes()));
    doc.getDocumentElement().normalize();
    XPath xPath =  XPathFactory.newInstance().newXPath();
    
    String expression = "/ns6:ReadPersonReturn/ns6:object/ns3:Person/ns3:Phone/ns3:item";
    NodeList nodes = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
    Element secondNode = null;
    if(nodes != null && nodes.getLength() > 0){
        secondNode = (Element) leadCloudPingRecordNodes.item(i);
    }
    
    0 讨论(0)
提交回复
热议问题