如何从具有名称空间的xml文件中提取值?

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

我有下面显示的xml文件,该文件具有名称空间,我正在尝试为其提取Node24的值

我当前的代码在下面,没有打印任何内容:

import xml.etree.ElementTree as ET

filename = 'ifile.xml'
tree = ET.parse(filename)
root = tree.getroot()

for neighbor in root.iter('Node24'):
    print(neighbor)

我的预期输出将是:

03-c34ko
04-c64ko
07-c54ko  

这是ifile.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data-main-43:DATAMAINXZ123 xmlns="https://example.com/DATA-MAIN-XZ123" xmlns:data-gen="https://example.com/DATA-GEN" xmlns:data-main-43="https://example.com/DATA-MAIN-XZ123" xmlns:xsi="http://www.w3.org/2011/XMLSchema-instance" xsi:schemaLocation="https://example.com/DATA-MAIN-XZ123 data-main-ir21-12.1.xsd">
  <MAINXZ123FileHeader>
    <DATAGenSchemaVersion>2.4</DATAGenSchemaVersion>
    <DATAMAINXZ123SchemaVersion>12.1</DATAMAINXZ123SchemaVersion>
  </MAINXZ123FileHeader>
  <Node1>
    <Node2>WTRT DDK</Node2>
    <Node3>XYZW</Node3>
    <Node4>
      <Node5>
        <Node6>XYZW882</Node6>
        <Node5Type>Ter</Node5Type>
        <Node5Data>
          <Node9>
            <Node10>
              <Node11>2019-02-18</Node11>
              <Node12>
                <Node13>
                  <Node14>
                    <Node15>Ermso</Node15>
                    <Node16>
                      <PrimaryNode16>
                        <Node18>19.32</Node18>
                        <Node18>12.11</Node18>
                      </PrimaryNode16>
                      <SecondaryNode16>
                        <Node18>82.97</Node18>
                        <Node18>12.41</Node18>
                      </SecondaryNode16>
                    </Node16>
                    <Node20>Muuatippw</Node20>
                  </Node14>
                </Node13>
              </Node12>
              <Node21>
                <Node22>
                  <Node23>
                    <Node24>03-c34ko</Node24>
                    <Node24>04-c64ko</Node24>
                    <Node24>07-c54ko</Node24>
                  </Node23>
                  <Node26Node22EdgeAgent>
                    <Node26>jjkksonem</Node26>
                    <PrimaryNode18DEANode26>
                      <Node18>2.40</Node18>
                    </PrimaryNode18DEANode26>
                  </Node26Node22EdgeAgent>
                </Node22>
              </Node21>
              <Node28>
                <Node29>
                  <Node30>false</Node30>
                  <Node31>true</Node31>
                </Node29>
              </Node28>
            </Node10>
          </Node9>
        </Node5Data>
      </Node5>
    </Node4>
  </Node1>
</data-main-43:DATAMAINXZ123>

我该怎么做?预先感谢。

python xml xml-parsing xml-namespaces elementtree
1个回答
1
投票

我使用正则表达式,所以这是一个替代答案。我将xml转换为字符串,然后搜索Node24之间的所有字符串

© www.soinside.com 2019 - 2024. All rights reserved.