簡體   English   中英

如何使用python(xml.etree.ElementTree)解決下一個問題?

[英]How to address the next iter with python (xml.etree.ElementTree)?

  <storage>
    <record>
      <values>
        <points>99999999</points>
        <points>Mr</points>
        <points>Marvin</points>
        <points>Homes</points>
        <points>hardware</points>
        <points>true</points>
        <points>de</points>
        <points>6</points>
        <points>false</points>
      </values>
    </record>
  </storage>

你好,

我試圖用python(xml.etree.ElementTree)更改一些xml值。 這是xml數據的一小部分。

appelation=re.compile("Mr")
for fname in root.iter('points'):

    if appelation.match(str(pTest)):
        fname.text="New Mr/Mrs"
        ## here i am trying to edit the next iter (<points>Marvin</points>)
        ##fname.next().text="New name" -> doesnt work

有任何建議如何解決下一個iter? xml文件有很多名為<“points”>的標簽,值總是不同的。

我假設您使用的是xml.etree.ElementTree因為它是標准庫的一部分。 請考慮以下代碼段:

appelation = re.compile('Mr')
points = root.iter('points')
for node in points:
    if appelation.match(node.text):
        node.text = 'Monsieur'
        node = next(points)
        node.text = 'Francois'
        break

ElementTree.dump(根)

在這個片段中, points是一個可迭代的,我們用它來獲取下一個點和搜索。 一旦我們找到了我們正在尋找的節點(Mr),我們就可以對該節點和下一個節點做一些事情(通過在所述迭代上調用next )。

輸出:

<storage>
    <record>
      <values>
        <points>99999999</points>
        <points>Monsieur</points>
        <points>Francois</points>
        <points>Homes</points>
        <points>hardware</points>
        <points>true</points>
        <points>de</points>
        <points>6</points>
        <points>false</points>
      </values>
    </record>
  </storage>

更新

如果要修改此節點,下一個節點和上一個節點; 那么你需要跟蹤前一個節點,因為迭代器無法返回。 最簡單的方法是使用堆棧( listcollections.deque會這樣做):

appelation = re.compile('Mr')
points = root.iter('points')
nodes_stack = []
for node in points:
    if appelation.match(node.text):
        # Modify this node
        node.text = 'Monsieur'

        # Modify next node
        next_node = next(points)
        next_node.text = 'Francois'

        # Modify previous node
        previous_node = nodes_stack.pop()
        previous_node.text = 'modified'

        # Keep popping the stack the get to previous nodes
        # in reversed order

        ElementTree.dump(root)
        break
    else:
        nodes_stack.append(node)

暫無
暫無

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

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