【问题标题】:Access XML Element Values with Python使用 Python 访问 XML 元素值
【发布时间】:2018-06-27 17:07:10
【问题描述】:

我是 Python 新手,所以如果之前已经介绍过这个问题并且我太无知而无法应用该解决方案,我深表歉意。

这是 XML:

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>DEFAULT</groupId>
  <artifactId>ADP_ServiceTechnology-JRG_Testing</artifactId>
  <version>2.0.31</version>
  <dependencies>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>ADP Standard Operations</artifactId>
      <version>2.2.86.17-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>Base</artifactId>
      <version>1.9.0-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>Databases</artifactId>
      <version>[1.1.0]</version>
    </dependency>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>HPE Solutions</artifactId>
      <version>[1.8.2]</version>
    </dependency>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>Business Applications</artifactId>
      <version>[1.3.0]</version>
    </dependency>
    <dependency>
      <groupId>DEFAULT</groupId>
      <artifactId>Operating Systems</artifactId>
      <version>[1.3.0]</version>
    </dependency>
  </dependencies>
</project>

我成功导入数据:

import xml.etree.ElementTree as ET
tree = ET.parse('pom.xml')
root = tree.getroot()

我只需要遍历树并检索 &lt;artifactId&gt;&lt;version&gt; 值。我尝试了许多在网上找到的方法,但都没有运气。使用 php 和 xpath 对我来说很简单,但是 python 让我很难过。

这个:

for elem in tree.iter():
  print "%s: '%s'" % (elem.tag, elem.text)  

将返回每个元素标记和文本,但我只想导航到我指出的两个。

提前致谢!

【问题讨论】:

    标签: python xml parsing


    【解决方案1】:

    如果你在命名空间前面加上它们,你可以找到它们:

    import xml.etree.ElementTree as ET
    tree = ET.parse("t.xml")
    root = tree.getroot()
    
    namesp = root.tag.replace("project","")  # get the namesapce from the root key
    
    version = root.find(namesp+"version")
    artifactId = root.find(namesp+"artifactId")
    
    print(version.text)
    print(artifactId.text)
    

    输出:

    2.0.31
    ADP_ServiceTechnology-JRG_Testing 
    

    您可以在此处找到更多一般信息:Parsing XML in Python using ElementTree example

    在 doku https://docs.python.org/3/library/xml.etree.elementtree.html(在页面顶部切换到 python 2)

    如果您想从数据中剥离命名空间,请参阅 https://stackoverflow.com/a/25920989/7505395Python ElementTree module: How to ignore the namespace of XML files to locate matching element when using the method "find", "findall"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 2021-05-06
      • 2019-06-17
      相关资源
      最近更新 更多