0
import xml.dom.minidom

content = """
<urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
  <url>
    <loc>http://www.domain.com/</loc>
    <lastmod>2011-01-27T23:55:42+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.domain.com/page1.html</loc>
    <lastmod>2011-01-26T17:24:27+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>  
  <url>
    <loc>http://www.domain.com/page2.html</loc>
    <lastmod>2011-01-26T15:35:07+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>  
</urlset>
"""

xml = xml.dom.minidom.parseString(content)
urlset = xml.getElementsByTagName("urlset")[0]
url = urlset.getElementsByTagName("url")

for i in range(0, url.length):
    loc = url[i].getElementsByTagName("loc")[0].childNodes[0].nodeValue
    lastmod = url[i].getElementsByTagName("lastmod")[0].childNodes[0].nodeValue
    changefreq = url[i].getElementsByTagName("changefreq")[0].childNodes[0].nodeValue
    priority = url[i].getElementsByTagName("priority")[0].childNodes[0].nodeValue
    print "%s, %s, %s, %s" % (loc, lastmod, changefreq, priority)

ノードの値を取得する簡単な方法はありませんか?

loc = url[i].getElementsByTagName("loc")[0].childNodes[0].nodeValue
4

4 に答える 4

0

これは機能しますloc = getElementsByTagName("loc")[i].innerHTMLか?

于 2012-08-03T07:16:33.033 に答える
0

ノードの値を取得するためのより良い方法があるかもしれません...しかし、これは少なくとも、自分自身を繰り返さないよりクリーンな代替手段です:

import xml.dom.minidom

content = """
<urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
  <url>
    <loc>http://www.domain.com/</loc>
    <lastmod>2011-01-27T23:55:42+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.domain.com/page1.html</loc>
    <lastmod>2011-01-26T17:24:27+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>  
  <url>
    <loc>http://www.domain.com/page2.html</loc>
    <lastmod>2011-01-26T15:35:07+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>  
</urlset>
"""

def get_first_node_val(obj, tag):
    return obj.getElementsByTagName(tag)[0].childNodes[0].nodeValue

xml = xml.dom.minidom.parseString(content)
urlset = xml.getElementsByTagName("urlset")[0]
urls = urlset.getElementsByTagName("url")

for url in urls:
    loc = get_first_node_val(url, "loc")
    lastmod = get_first_node_val(url, "lastmod")
    changefreq = get_first_node_val(url, "changefreq")
    priority = get_first_node_val(url, "priority")
    print "%s, %s, %s, %s" % (loc, lastmod, changefreq, priority)
于 2012-08-03T07:25:42.783 に答える
0

ノードの最初の子ではない理由

loc = url[i].getElementsByTagName("loc").firstChild.nodeValue
于 2012-08-03T07:26:56.273 に答える