元素树xml

时间:2016-03-31 10:33:17

标签: python xml elementtree

我无法理解为什么在尝试达到时间戳时出现错误。 XML格式(省略一些属性):

编辑:这是xml文件的实际类型。

<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>

但是当我尝试以下内容时:

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

我收到错误

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

2 个答案:

答案 0 :(得分:1)

您正在迭代每个标记,因此显然在每个标记上使用.find将返回None,因此您的错误:

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

id
timestamp
contributor
comment
model

使用您自己的方法,您必须检查每个标记:

xml = fromstring(xml)

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

您可以使用findall获取所有修订标记,然后提取时间戳:

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']

如果您使用lxml,则可以使用简单的xpath表达式:

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']

根据您发布的内容,您需要使用命名空间映射:

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) ]

假设所有修订标记都有一个时间戳标记。

或者使用带xpath的lxml:

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))

如果您打印

tree = parse("test.xml")

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

输出结果为:

{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
.............................

答案 1 :(得分:0)

我会做一些像:

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

如果你的xml有多个时间戳元素,我会改为最后一行:

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