Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在xml中搜索文本并返回元素/节点_Python_Xml_Search_Text - Fatal编程技术网

Python 在xml中搜索文本并返回元素/节点

Python 在xml中搜索文本并返回元素/节点,python,xml,search,text,Python,Xml,Search,Text,我希望能够通过文本值搜索xml格式的文件,并返回它所包含的id。我浏览了python库中的xml命令,但只看到了按元素/节点搜索的示例。我在下面有一个简化的xml示例,我想搜索“3x3眼睛”并返回“2”。它还应该搜索精确的文本减号大小写。每个动画下通常会有多个标题条目,因此搜索可以在第一次匹配时停止。谢谢 <?xml version="1.0" encoding="UTF-8"?> <animetitles> <anime aid="1"> <

我希望能够通过文本值搜索xml格式的文件,并返回它所包含的id。我浏览了python库中的xml命令,但只看到了按元素/节点搜索的示例。我在下面有一个简化的xml示例,我想搜索“3x3眼睛”并返回“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>

星冠
星冠
3x3眼
3x3双眼睛:神魔传说
第一个返回
[2]
,第二个返回
[2,3]

或者有点神秘,但是,嘿,为什么不:)


您可以使用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

另请参阅。

您想要完全匹配还是部分匹配?这个例子应该只返回2或[2,3]?最初我是在寻找精确的匹配,但是因为你提到了我可能会从开始,因为我正在做的事情的性质。无论哪种方式,我对如何搜索文本都有大致的想法,因此这之后是一件小事。另外,我只是在寻找第一个匹配,现在也很容易添加。谢谢你的代码。这正是我要找的。我可能会改变它与文本的匹配方式,这取决于我想对我的脚本做什么。
results = [anime.get('aid') for anime in tree.findall('anime')
           for title in anime.findall('title') if title.text == '3x3 Eyes']
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