M.Pickard
M.Pickard

Reputation: 1

Parsing subtags XML in Python

I have this XML:

<SwitchPort name="1110" portType="RS422_Board2">
<Bus>UO-2-3</Bus>
<Device>FC3</Device>
<Appearance>Simulated</Appearance>
</SwitchPort>

I can get the portType using:

for node in NCFile.getElementsByTagName("SwitchPort"):
    portType = node.getAttribute("portType")

But I want to get the values of Apperance, Device, etc.

What am I doing wrong?

Matt

Upvotes: 0

Views: 34

Answers (2)

PKD
PKD

Reputation: 194

you can use lxml for parsing xml - lxml

from lxml import etree

root_element = etree.fromstring(xml_string)

device_node_value = root_element.findtext('Device')

Upvotes: 0

rafaelc
rafaelc

Reputation: 59284

Simply use getElementsBytagName on your node and get the nodeValue

for node in NCFile.getElementsByTagName("SwitchPort"):
    portType = node.getAttribute("portType")
    device = node.getElementsByTagName("Device")[0].firstChild.nodeValue
    appearance = node.getElementsByTagName("Appearance")[0].firstChild.nodeValue

Upvotes: 1

Related Questions