The element tree xml

倖福魔咒の 提交于 2019-12-10 22:22:00

问题


I can't figure why I get an error while trying to reach the timestamp. XML format (left out some attributes):

EDIT: this is the actual type of the xml file.

<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.10/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.10/ http://www.mediawiki.org/xml/export-0.10.xsd" version="0.10" xml:lang="en">
    <siteinfo>
        <sitename>Wikipedia</sitename>
        <dbname>enwiki</dbname>
        <base>https://en.wikipedia.org/wiki/Main_Page</base>
        <generator>MediaWiki 1.27.0-wmf.18</generator>
        <case>first-letter</case>
        <namespaces>...</namespaces>
    </siteinfo>
    <page>
        <title>Zhuangzi</title>
        <ns>0</ns>
        <id>42870472</id>
        <revision>
            <id>610251969</id>
            <timestamp>2014-05-26T20:08:14Z</timestamp>
            <contributor>
                <username>White whirlwind</username>
                <id>8761551</id>
            </contributor>
            <comment>...</comment>
            <model>wikitext</model>
            <format>text/x-wiki</format>
            <text xml:space="preserve" bytes="41">#REDIRECT [[Zhuang Zhou]] {{R from move}}</text>
            <sha1>9l31fcd4fp0cfxgearifr7jrs3240xl</sha1>
        </revision>
        <revision>...</revision>
        <revision>...</revision>
        <revision>...</revision>
        <revision>...</revision>
        <revision>...</revision>

    </page>
    <page>...</page>
</mediawiki>

But when I'm trying the following:

for page in root:          
  for revision in page:
    print(revision.find('timestamp').text)

I get the error

   print(revision.find('timestamp').text)
   AttributeError: 'NoneType' object has no attribute 'text'

回答1:


You are iterating over each tag so obviously using .find on every tag is going to return None hence your error:

In [9]: for page in root:
            print(page.tag)
            for revision in page:
                  print(revision.tag)
   ...:         

id
timestamp
contributor
comment
model

using your own method you would have to check each tag:

xml = fromstring(xml)

for page in xml:
    for revision in page:
      if revision.tag == "timestamp":
          print(revision.text)

You can use findall to get all the revision tags and then extract the timestamps:

In [1]: xml = """<page>
   ...:    <title>Zhuangzi</title>
   ...:    <ns>0</ns>
   ...:    <id>42870472</id>
   ...:    <revision>
   ...:       <id>610251969</id>
   ...:       <timestamp>2014-05-26T20:08:14Z</timestamp>
   ...:       <contributor>
   ...:          <username>White whirlwind</username>
   ...:          <id>8761551</id>
   ...:       </contributor>
   ...:       <comment>TEXT</comment>
   ...:       <model>wikitext</model>
   ...:    </revision>
   ...: </page>"""

In [2]: import xml.etree.ElementTree as ET

In [3]: from StringIO import StringIO

In [4]: tree = ET.parse(StringIO(xml))

In [5]: root = tree.getroot()


In [6]: print([r.find("timestamp").text for r in root.findall("revision")])
['2014-05-26T20:08:14Z']

If you used lxml, you could use a simple xpath expression:

from lxml.etree import parse,fromstring

xml = """<page>
   <title>Zhuangzi</title>
   <ns>0</ns>
   <id>42870472</id>
   <revision>
      <id>610251969</id>
      <timestamp>2014-05-26T20:08:14Z</timestamp>
      <contributor>
         <username>White whirlwind</username>
         <id>8761551</id>
      </contributor>
      <comment>TEXT</comment>
      <model>wikitext</model>
   </revision>
</page>"""


root = fromstring(xml)

print(root.xpath("//revision/timestamp/text()"))
['2014-05-26T20:08:14Z']

With what you have posted you need to use a namespace mapping:

tree = ET.parse("your_xml")
root = tree.getroot()
ns = {"wiki":"http://www.mediawiki.org/xml/export-0.10/"}


ts = [ts.text for ts in root.findall(".//wiki:revision//wiki:timestamp", ns) ]

Presuming all the revision tags have a timestamp tag.

Or using lxml with an xpath:

from lxml.etree import parse


tree = parse("your_fie")
ns = {"wiki": "http://www.mediawiki.org/xml/export-0.10/"}

print(tree.xpath("//wiki:revision//wiki:timestamp//text()",namespaces=ns))

If you print

tree = parse("test.xml")

for elem in tree.getiterator():
    print elem.tag

The output is:

{http://www.mediawiki.org/xml/export-0.10/}mediawiki
{http://www.mediawiki.org/xml/export-0.10/}siteinfo
{http://www.mediawiki.org/xml/export-0.10/}sitename
{http://www.mediawiki.org/xml/export-0.10/}dbname
{http://www.mediawiki.org/xml/export-0.10/}base
{http://www.mediawiki.org/xml/export-0.10/}generator
{http://www.mediawiki.org/xml/export-0.10/}case
{http://www.mediawiki.org/xml/export-0.10/}namespaces
{http://www.mediawiki.org/xml/export-0.10/}page
.............................

.




回答2:


I would simply do something like:

import xml.etree.ElementTree as ET
root = ET.parse('your_xml_file.xml')
timestamp = root.find('.//timestamp').text

If your xml has got more than one timestamp element I would change last line with:

timestamps = [t.text for t in root.findall('.//timestamp')]


来源:https://stackoverflow.com/questions/36330902/the-element-tree-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!