簡體   English   中英

python lxml如何將文本屬性的引用作為值添加到列表中

[英]python lxml how to add reference of text attribute as value to list

我有一個用 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字符串附加到列表中:

蟒蛇代碼:

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM