Parse xml nodes having text with any namespace using jsoup

后端 未结 1 479
一向
一向 2020-12-21 23:50

I am trying to parse XML from URL using Jsoup.

In this given XML there are nodes with namespace.

for ex:

相关标签:
1条回答
  • 2020-12-22 00:26

    There is no such selector (yet). But you can use a workaround - a not as easy to read like a selector, but it's a solution.

    /*
     * Connect to the url and parse the document; a XML Parser is used
     * instead of the default one (html)
     */
    final String url = "http://www.consultacpf.com/webservices/producao/cdc.asmx?wsdl";
    Document doc = Jsoup.connect(url).parser(Parser.xmlParser()).get();
    
    
    // Elements of any tag, but with 'types' are stored here
    Elements withTypes = new Elements();
    
    // Select all elements
    for( Element element : doc.select("*") )
    {
        // Split the tag by ':'
        final String s[] = element.tagName().split(":");
    
        /*
         * If there's a namespace (otherwise s.length == 1) use the 2nd
         * part and check if the element has 'types'
         */
        if( s.length > 1 && s[1].equals("types") == true )   
        {
            // Add this element to the found elements list
            withTypes.add(element);
        }
    }
    

    You can put the essential parts of this code into a method, so you get something like this:

    Elements nsSelect(Document doc, String value)
    {
        // Code from above
    }
    
    ...
    
    Elements withTypes = nsSelect(doc, "types");
    
    0 讨论(0)
提交回复
热议问题