Parsing XML Android - tag parsing

前端 未结 3 1003
天涯浪人
天涯浪人 2021-01-13 17:36

im trying to build an app to read this feed: http://loc.grupolusofona.pt/index.php/?format=feed

Its working just fine, except for the fact that when it reaches the

相关标签:
3条回答
  • 2021-01-13 18:31
    public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
    }
    

    you are using this code which give null while parsing description.

    I try your code and to get the content of description.

    I use

    child.getTextContent()
    

    and it give me the content.

    Change your code to

    public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
     if (elem.hasChildNodes()){
         for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
             if(child.getNodeName().equalsIgnoreCase("description"))
             {
                 return child.getTextContent();
             }
             if( child.getNodeType() == Node.TEXT_NODE  ){
                 return child.getNodeValue();
             }
         }
     }
     }
     return "";
    }
    

    And you got the content of description as well..,. Try it..,.

    0 讨论(0)
  • 2021-01-13 18:34

    The problem, I think, is that the <description> tags that are returned by that site all contain <![CDATA[ sections, not text. Your code for XMLParser.getElementValue only returns values for TEXT nodes. Change this:

    if( child.getNodeType() == Node.TEXT_NODE  ){
        return child.getNodeValue();
    }
    

    to:

    if( child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_NODE ){
        return child.getNodeValue();
    }
    
    0 讨论(0)
  • 2021-01-13 18:37

    The description tag contains a CDATA element. Therefore it's not a text node so your check for

    if( child.getNodeType() == Node.TEXT_NODE  )
    

    will be false for those nodes. The child is most likely a CDATA_SECTION_NODE. It's also possible that the node has multiple children (text nodes if there is text outside the CDATA including whitespace) and you'll need to handle selecting the right child in that case.

    0 讨论(0)
提交回复
热议问题