如何在xml中访问单个信息

问题描述 投票:0回答:1

当前,我正在尝试从csv中的数据修改xml。为此,我正在使用pandas数据框访问csv中的数据。我也想从xml访问单个信息,并用csv中的数据覆盖xml中的数据。

因此,我为csv编写了功能,但是我不知道如何访问xml数据,因此,如果有人可以帮助我,那真的很酷。

        <Test Testbench="3" Result="PASSED" Name="8">
            <SubTests>
                <SubTest Result="PASSED" Name="8_1">
                    <Measurement Name="U5" Type="Number">
                        <Number>
                            <Value>9.300001</Value>
                            <Unit>V</Unit>
                        </Number>
                    </Measurement>
                </SubTest>
                <SubTest Result="PASSED" Name="8_2">
                    <Measurement Name="U6" Type="Number">
                        <Number>
                            <Value>3.099975</Value>
                            <Unit>V</Unit>
                        </Number>
                    </Measurement>
                </SubTest>
                <SubTest Result="PASSED" Name="8_3">
                    <Measurement Name="U7" Type="Number">
                        <Number>
                            <Value>11.500010</Value>
                            <Unit>V</Unit>
                        </Number>
                    </Measurement>
                </SubTest>
                <SubTest Result="PASSED" Name="8_4">
                    <Measurement Name="U8" Type="Number">
                        <Number>
                            <Value>3.199975</Value>
                            <Unit>V</Unit>
                        </Number>
                    </Measurement>
                </SubTest>
            </SubTests>
        </Test>

例如,如何访问xml中的3.199975值

我想保存这样的输出。

print(Function)

3.199975
python xml python-3.5
1个回答
0
投票
import xml.etree.ElementTree as ET


root = ET.fromstring(x) # or ET.parse(file_path) if loading from a file

# prints 3.199975, searching by Measurement's Name attribute
print(root.findall(".//Measurement[@Name='U8']/Number/Value")[0].text)

# get all values in a list
print([i.text for i in root.findall(".//Measurement/Number/Value")])
© www.soinside.com 2019 - 2024. All rights reserved.