Created
January 9, 2015 03:10
-
-
Save lmatt-bit/1642dab91aadce5c22a4 to your computer and use it in GitHub Desktop.
Handle default namespace in xml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from lxml import etree | |
| from StringIO import StringIO | |
| s = '''<?xml version="1.0" encoding="UTF-8"?> | |
| <Environment | |
| xmlns="http://schemas.dmtf.org/ovf/environment/1" | |
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
| xmlns:oe="http://schemas.dmtf.org/ovf/environment/1" | |
| xmlns:ve="http://www.vmware.com/schema/ovfenv" | |
| oe:id="" | |
| ve:vCenterId="vm-61"> | |
| <PlatformSection> | |
| <Kind>VMware ESXi</Kind> | |
| <Version>5.5.0</Version> | |
| <Vendor>VMware, Inc.</Vendor> | |
| <Locale>en</Locale> | |
| </PlatformSection> | |
| <PropertySection> | |
| <Property oe:key="ppEnv" oe:value="production"/> | |
| <Property oe:key="pphostname" oe:value="coolhostname"/> | |
| </PropertySection> | |
| <ve:EthernetAdapterSection> | |
| <ve:Adapter ve:mac="00:50:56:94:9a:56" ve:network="Service" ve:unitNumber="7"/> | |
| </ve:EthernetAdapterSection> | |
| </Environment>''' | |
| f = StringIO(s) | |
| tree = etree.parse(f) | |
| oe = '{http://schemas.dmtf.org/ovf/environment/1}' | |
| namespaces={'oe': 'http://schemas.dmtf.org/ovf/environment/1', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 've': 'http://www.vmware.com/schema/ovfenv'} | |
| print tree.xpath('//oe:Property', namespaces=namespaces) | |
| #output [<Element {http://schemas.dmtf.org/ovf/environment/1}Property at 0xf936f88>, <Element {http://schemas.dmtf.org/ovf/environment/1}Property at 0xf941088>] | |
| print tree.xpath('//oe:Property[@oe:key="pphostname"]/@oe:value', namespaces=namespaces) | |
| #output ['coolhostname'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment