Home > Back-end >  Extract the Kth tag data in XML using ElementTree
Extract the Kth tag data in XML using ElementTree

Time:02-23

Below is my current XML file (output.xml), and I hope that I can get its tag value using Python. It is an XML file with namespace.

<data xmlns="urn:ietf:params:ns:netconf:base:1.0">
  <interfaces xmlns="http://namespace.net">
    <interface>
      <name>Interface0</name>
    </interface>
    <interface>
      <name>Interface1</name>
    </interface>
    <interface>
      <name>Interface2</name>
    </interface>
  </interfaces>
</data>
              

And...below is my Python code to extract the value of tag <interface>:

from xml.etree import cElementTree as ET

tree = ET.ElementTree(file="output.xml")
root = tree.getroot()

nsmap = {'':'http://namespace.net'}  # namespace

for name in root.iterfind('./interfaces/interface/name', namespaces=nsmap):
   print(name.text)

My question is:

Is it possible to only fetch "Interface0", "Interface1", or "Interface2"?

If there are multiple <interface> tags, can I only fetch the values of the tags within the kth <interface>?

CodePudding user response:

Use enumerate to get an enumerate object.

for index, name in enumerate(root.iterfind('./interfaces/interface/name', namespaces=nsmap)):
    # if index <= kth:
    if index == 0:# 1, 2?
        print(name.text)

CodePudding user response:

If Interface0, Interface1, ..., InterfaceN always come in sorted order then you don't require the sorted() function. Just remove it in that case.

To pick Kth value:-

import xml.etree.ElementTree as ET

tree = ET.parse("output.xml")
root = tree.getroot()

k = 3 # put the value assuming index starts with 0
sorted(list(map(lambda x: x.text, root.findall("./interfaces/interface/name", namespaces=nsmap))))[k]

To get within Kth values:-

import xml.etree.ElementTree as ET

tree = ET.parse("output.xml")
root = tree.getroot()

k = 3 # put the limit assuming index starts with 0
sorted(list(map(lambda x: x.text, root.findall("./interfaces/interface/name", namespaces=nsmap))))[:k]
  • Related