[Python] Python for xml parsing, how to track correct tree

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I try to parse XML file to get NeedThisValue!!! for one of the element tagged <Value>. But there are several tags <Value> in file. How I can get the right one under <Image> branch? This is example of my XML:

    <Report xmlns=http://schemas.microsoft.com>
    <AutoRefresh>0</AutoRefresh>
    <DataSources>
    <DataSource Name="DataSource2">
    <Value>SourceAlpha</Value>
    <rd:SecurityType>None</rd:SecurityType>
    </DataSource>
    </DataSources>
    <Image Name="Image36">
    <Source>Embedded</Source>
    <Value>NeedThisValue!!!</Value>
    <Sizing>FitProportional</Sizing>
    </Image>
    </Report>


    And I'm using this code:

    from bs4 import BeautifulSoup

    with open(filepath, 'r') as f:
    data = f.read()
    Bs_data = BeautifulSoup(data, "xml")
    b_unique = Bs_data.find_all('Value')
    print(b_unique)

    ### result is below, I need second one only.
    [<Value>SourceAlpha</Value>, <Value>NeedThisValue!!!</Value>]

    Continue reading...

Compartilhe esta Página