简体   繁体   English

尝试使用python中的元素树解析xml行以获取与标签关联的特定值

[英]Trying to parse xml line for specific values associated with a tag using element tree in python

I am currently struggling trying to figure out how to parse out specific information from a specific tag that is in a xml file.我目前正在努力弄清楚如何从 xml 文件中的特定标签中解析出特定信息。

The xml file is structured as such xml文件的结构是这样的

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <configSections>
        |
        |
   </configSections>
   <connectionStrings>
        <clear />
        <add name="Database1" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user2;Password=oogabooga1" providerName="Database1provider"/>
        <add name="Database12" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user1;Password=oogabooga2" providerName="Database2provider"/>

   </connectionStrings>

I am trying to parse out the name, UserId and Password from connectionStrings.我正在尝试从 connectionStrings 中解析出名称、用户 ID 和密码。

I am stuck on trying to get parse out the data using Element Tree, any ideas here?我一直在尝试使用元素树解析数据,这里有什么想法吗?

import xml.etree.ElementTree as ET

webconfig = etree.parse(filepath)

from elem in webconfig.findall('configuration'):
    print(elem.text)

Any help is greatly appreciated任何帮助是极大的赞赏

Does this help?这有帮助吗?


import xml.etree.ElementTree as ET

someXML = '''<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <configSections>
        |
        |
   </configSections>
   <connectionStrings>
        <clear />
        <add name="Database1" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user2;Password=oogabooga1" providerName="Database1provider"/>
        <add name="Database12" connectionString="DataSource=[ServerName];Initial Catalog=[DatabaseName]; User ID=user1;Password=oogabooga2" providerName="Database2provider"/>
   </connectionStrings>
</configuration>
'''

data = ET.fromstring(someXML)

for i in data.findall('connectionStrings'):
    for item in i.findall('add'):
        print(item.attrib)

Please note there were several syntax issues in your XML which I cleaned up.请注意,我清理了您的 XML 中的几个语法问题。

Also, if you need to get individual key value pairs, you can use this:此外,如果您需要获取单独的键值对,您可以使用:


for i in data.findall('connectionStrings'):
    for item in i.findall('add'):
        print(item.get('name'))

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

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