Has the following XML
<Axmlns= "Http://This/is/a/namespace"> <B>DataB1</B> <B>DataB2</B> <B> <C>Datac</C> </B></A>
Where the xmlns attribute represents the default namespace for the XML, which must be a URL form
View the tag for XML
#encoding =utf8from lxml Import etreestr_xml = "" "<Axmlns= "Http://This/is/a/namespace"> <B>DataB1</B> <B>DataB2</B> <B> <C>Datac</C> </B></A>"" " XML = etree.fromstring (Str_xml) for node in Xml.iter (): Print Node.tag
The result is:
{Http://This/is/a/namespace} A{http://this/is/a/namespace}b{http://this/is/a/namespace}b{http://this/is/a/namespace}b{http://this/is/a/namespace}c
As you can see, there is a namespace in front of each tag compared to the normal XML tag.
Gets the namespace. Nsmap
From lxml Import etreestr_xml = "" "<Axmlns= "Http://This/is/a/namespace"> <B>DataB1</B> <B>DataB2</B> <B> <C>Datac</C> </B></A>"" " XML = etree.fromstring (str_xml) ns = Xml.nsmapprint nsprint Ns[none]
Results
{None: ' Http://This/is/a/namespace '}http://this/is/a/namespace
Ns[none] Gets the default namespace, NS displays all namespaces
Gets the contents of a node with a namespace
fromlxmlImportEtreestr_xml="""<a xmlns= "Http://This/is/a/namespace" > <B>dataB1</B> <B>dataB2</B> <B> <C>dataC</C> </B></A>"""XML=etree.fromstring (str_xml) NS=Xml.nsmap[none]ns="{%s}"%NS forIteminchXml.findall ("{0}b/{0}c". Format (NS)):#cannot use XPath to make an error PrintItem.text
Results
Datac
Note that each level node needs to be prefixed with a namespace when looking for a node. And the test found that findall can normally find information, and XPath will error.
Gets the property value with the namespace node
fromlxmlImportEtreestr_xml="""<a xmlns= "Http://This/is/a/namespace" > <b b= "123" >dataB1</B> <B>dataB2</B> < b> <C>dataC</C> </B></A>"""XML=etree.fromstring (str_xml) NS=Xml.nsmap[none]ns="{%s}"%Nsitem= Xml.find (ns+"B")Print item.get ("b") PrintItem.text
Results
123DataB1
You can see that when you get a property, you don't need to add a namespace, just get it.
"Python" lxml processing namespaces