0

テキスト値で xml 形式のファイルを検索し、その一部である ID を返すことができるようにしたいと考えています。私はxmlコマンドでpythonライブラリを調べましたが、要素/ノードによる検索の例しか見ませんでした。以下に簡単な xml サンプルを示します。たとえば、「3x3 Eyes」を検索して「2」を返したいと思います。また、大文字と小文字を区別しない正確なテキストも検索する必要があります。通常、各アニメの下にタイトルのエントリが複数あるため、最初の一致で検索を停止できます。ありがとう

<?xml version="1.0" encoding="UTF-8"?>
<animetitles>
  <anime aid="1">
    <title type="official" xml:lang="fr">Crest of the Stars</title>
    <title type="official" xml:lang="fr">Crest of the Stars</title>
  </anime>
  <anime aid="2">
    <title type="official" xml:lang="en">3x3 Eyes</title>
  </anime>
  <anime aid="3">
    <title type="official" xml:lang="en">3x3 Eyes: Legend of the Divine Demon</title>
  </anime>
</animetitles>
4

2 に答える 2

1
tree = et.parse( ... )

# Unique match
results = []
for anime in tree.findall('anime'):
    for title in anime.findall('title'):
        if title.text == '3x3 Eyes':
            results.append(anime.get('aid'))
print results

# Everything that starts with
results = []
for anime in tree.findall('anime'):
    for title in anime.findall('title'):
        if title.text.startswith('3x3 Eyes'):
            results.append(anime.get('aid'))
print results

最初のものは戻り[2]、2番目のものは戻ります[2, 3]

または、もう少し不可解ですが、ねえ、なぜですか:)

results = [anime.get('aid') for anime in tree.findall('anime')
           for title in anime.findall('title') if title.text == '3x3 Eyes']
于 2013-08-18T01:19:41.967 に答える
0

ElementTree を目的に使用できます。

import xml.etree.ElementTree as ET
tree = ET.parse('a.xml')
root = tree.getroot()

def findParentAttrib(string):
    for neighbor in root.iter():
        for parent in neighbor.getiterator():
            for child in parent:
                if child.text == string:
                    return parent.attrib['aid']

print findParentAttrib("3x3 Eyes") # returns 2

こちらのページもご参照ください。

于 2013-08-18T01:37:44.610 に答える