python - Working with namespace while parsing XML using ElementTree -


This

complies with the question, I now get the namespace in my XML I am trying to understand the answer but the lower is more.

XML file.

  & lt; Project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns: Xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schema location = "http: / /maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> & Lt; Grandparent & gt; & Lt; Parents & gt; & Lt; Children & gt; Sam / Astronaut & lt; / Children & gt; & Lt; / Parent & gt; & Lt; / Grandparent & gt; & Lt; / Project & gt;  

  Import xml.etree.ElementTree after viewing ET as empty space = 'xmlns' My Pyro Code:' http: // Maven.apache Org / POM / 4.0.0 ',' Schema Locations': 'http: //maven.apache.org/xsd/maven-4.0.0.xsd'} tree = ET Find ('parent') for b in parse ("test.xml") a = tree .findall ('child', name space = spaces)): if b.text.strip () == 'j / Doctor ': The print "baby is present" break: ET.SubElement (A,' child '). Text = "J / Doctor" tree. Written ("test.xml")  

I get an error: Attribute error: 'Any type' object has no attributes on this line There are two problems:

  There are two problems on this line:  
  A = tree.find ('parent')  
< P> First, & lt; Parent & gt; The basic element does not have immediate child & lt; Parents & gt; is the grandson of the parent element, the parent path looks like / project / grandparent / parent & lt; Parent & gt; To search , try XPath expression * / parent or possibly // parent .

Second, & lt; Parents & gt; is present in the default namespace, so you will not be able to do .find () with its simple name. You will need to add a namespace.

There are two valid calls for the same as tree.find () , each of which has & lt; Parent & gt; node:

  a = tree.find ('* / {http://maven.apache.org/POM/4.0.0} guardian') a = tree.find ( 

Next, call findall () requires a namespace qualifier:

   a.findall ('Xmlns: child', namespaces = spaces)  

for B, the name space qualifier is required to call the new child element to use the shortcut name There can be a way, but I did not find it. I had to use the long form of the name.

  ET.SubElement (a, '{http://memo.apache.org/POM/4.0.0} children') .text Finally, your XML output looks ugly unless you give a default namespace :  
  tree.write ('test.xml).', Default_namespace = spaces ['xmlns']]  

unrelated to XML aspects, you I have made a wrong copy of my reply from the previous question with lines for else , if :

  Not for ... if ... for ... and ...  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -