简体   繁体   English

从XML搜索数据并使用python写入anothe xml文件

[英]search data from XML and writing to anothe xml file with python

I want to know what is the best method to search for data in XML and then once the match is found write all the section to another file, given the following xml: 我想知道什么是在XML中搜索数据的最佳方法,然后一旦找到匹配项,则将所有部分写入另一个文件,并给出以下xml:

<root>
    <title>
        <control>
            <id>001</id>
            <gas-type>gasoline</gas-type>
            <brand>honda</brand>
        </control>
    </title>
    <title>          
        <control>
            <id>002</id>
            <gas-type>diesel</gas-type>
            <brand>volvo</brand>
        </control>
    </title>
</root>

eg 例如

if the user input is id = '001' then take all the data within the: 如果用户输入为id ='001',则获取以下范围内的所有数据:

    <title>
        <control>
            <id>001</id>
            <gas-type>gasoline</gas-type>
            <brand>honda</brand>
        </control>
    </title>

and write it in a new file. 并将其写入新文件。

so far I found a way to search for the ID: 到目前为止,我找到了一种搜索ID的方法:

from xml.dom import minidom


mixml="""<root>
    <title>
        <control>
            <id>001</id>
            <gas-type>gasoline</gas-type>
            <brand>honda</brand>
        </control>
    </title>
    <title>          
        <control>
            <id>002</id>
            <gas-type>diesel</gas-type>
            <brand>volvo</brand>
        </control>
    </title>
</root>"""

user = input('id:')

xmldoc = minidom.parseString(mixml)


itemlist = xmldoc.getElementsByTagName("id")

for i in itemlist:
    if i.firstChild.nodeValue == user:

in compares the user input vs the id tag. in比较用户输入与id标签。

You can use BeautifulSoup. 您可以使用BeautifulSoup。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open(your_file,encoding="utf8"), 'html.parser')
contentgroup = soup.find_all('control')
myresult = [item for item in contentgroup if item.id.contents[0]=='001']

Result would be: 结果将是:

 [<control>
 <id>001</id>
 <gas-type>gasoline</gas-type>
 <brand>honda</brand>
 </control>]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM