代码之家  ›  专栏  ›  技术社区  ›  Bill

通过xml.dom.minidom处理RSS/RDF

  •  2
  • Bill  · 技术社区  · 14 年前

    ...
      <item rdf:about="http://weblist.me/">
        <title>WebList - The Place To Find The Best List On The Web</title>
        <dc:date>2009-12-24T17:46:14Z</dc:date>
        <link>http://weblist.me/</link>
        ...
      </item>
      <item rdf:about="http://thumboo.com/">
        <title>Thumboo! Free Website Thumbnails and PHP Script to Generate Web Screenshots</title>
        <dc:date>2006-10-24T18:11:32Z</dc:date>
        <link>http://thumboo.com/</link>
    ...
    

    相关代码为:

    def getText(nodelist):
        rc = ""
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc = rc + node.data
        return rc
    
    dom = xml.dom.minidom.parse(file)
    items = dom.getElementsByTagName("item")
    for i in items:
        title = i.getElementsByTagName("title")
        print getText(title)
    

    我想这会打印出每个标题,但我得到的基本上是空白输出。我肯定我做错了什么蠢事,但不知道是什么?

    1 回复  |  直到 14 年前
        1
  •  4
  •   Tamás    14 年前

    title 节点到 getText nodeType 不是的 node.TEXT_NODE . 您必须循环遍历节点的所有子节点,而不是 获取文本

    def getTextSingle(node):
        parts = [child.data for child in node.childNodes if child.nodeType == node.TEXT_NODE]
        return u"".join(parts)
    
    def getText(nodelist):
        return u"".join(getTextSingle(node) for node in nodelist)
    

    node.normalize() 打电话之前 getTextSingle 这确保了 node.TEXT\u节点 node.TEXT\u节点 .