python lxml 如何将文本属性的引用作为值添加到列表中

标签 python lxml

我有一个用 objectify 解析的 xml 对象:

<sources>
  <source type="IP">
    <id>1000</id>
    <ip_address>100.100.1.11</ip_address>
    <netmask>255.255.255.255</netmask>
    <cidr>32</cidr>
  </source>
</sources>

我想使用以下代码将带有“/”的 IP 地址值和苹果酒作为字符串添加到列表中:

if source.get('type') == 'IP':
    source_lst.append(source.ip_address.text)+'/'+str(source.cidr)

我得到一个包含对 xml 对象引用的列表,而不是字符串列表。当我使用以下代码打印列表中的对象时:

for x in i.sources:
    print x

我什么也没得到。但是使用etree.tostring:

  for x in i.sources:
        print etree.tostring(x)

它向我显示了完整的 XML 对象:

<source xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" type="IP"><id>989</id><ip_address>100.100.1.10</ip_address><netmask>255.255.255.255</netmask><cidr>32</cidr></source>

如果我只是将文本属性作为字符串添加到代码中,为什么我的代码会添加完整的 XML 对象?

根据我得到的评论,我决定更改代码,但我没有提供我期望的结果。

    sources = access_request.sources.findall('source')
    for source in sources:
        if source.get('type') == 'IP':
            ip_address = source.ip_address.text
            cidr = source.cidr.text
            my_string = ip_address+'/'+cidr
            print my_string
            source_lst.append(my_string)

使用“print mystring”我得到这一行:

100.100.1.10/32

但是当我尝试打印列表中的项目时,我仍然得到 xml 对象而不是字符串。

我发现了问题。与这部分代码无关。 问题可以删除。

最佳答案

我不知道为什么你的代码不起作用,因为它不是一个完整的示例。但我相信您希望从示例 XML 构造一个 ipaddr/cidr 字符串列表。以下是一些 lxml 代码,用于扫描源记录并将它们作为 ipadd/cidr 字符串附加到列表中:

Python 代码:

from lxml import etree

source_lst = []
sources = etree.fromstring(my_xml)
for source in sources.findall("source[@type='IP']"):
    ip_address = source.findtext('ip_address')
    cidr = source.findtext('cidr')
    source_lst.append(ip_address + '/' + cidr)

print(source_lst)

示例数据:

my_xml = """
    <sources>
      <source type="IP">
        <id>1000</id>
        <ip_address>100.100.1.11</ip_address>
        <netmask>255.255.255.255</netmask>
        <cidr>32</cidr>
      </source>
      <source type="IPx">
        <id>1000</id>
        <ip_address>100.100.1.12</ip_address>
        <netmask>255.255.255.0</netmask>
        <cidr>24</cidr>
      </source>
      <source type="IP">
        <id>1000</id>
        <ip_address>100.100.1.13</ip_address>
        <netmask>255.255.255.0</netmask>
        <cidr>24</cidr>
      </source>
    </sources>
"""

打印:

['100.100.1.11/32', '100.100.1.13/24']

关于python lxml 如何将文本属性的引用作为值添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924380/

相关文章:

python - Lxml 元素与 namespace 相等

python - 我有 lxml 但仍然要求我安装它

java - Groovy:为什么按空格拆分()空字符串会返回一个空字符串列表?

python - 返回嵌套列表中元素的函数

Python AWS Boto URL 连接错误

Python lxml 使用 xi :include with multiple Xml fragments

python - 无法使用 lxml Xpath 解析器解析 html

python - 使用 lxml 查找 url 链接的文字文本

python - 在 python 中验证评论的最佳正则表达式是什么?

python - 如何在字符串中定义过滤器或表达式?