0

Example xml:

<response version-api="2.0">
  <value>
    <books>
        <book available="20" id="1" tags="">
            <title></title>
            <author id="1" tags="Joel">Manuel De Cervantes</author>
        </book>
        <book available="14" id="2" tags="Jane">
            <title>Catcher in the Rye</title>
           <author id="2" tags="">JD Salinger</author>
       </book>
       <book available="13" id="3" tags="">
           <title></title>
           <author id="3">Lewis Carroll</author>
       </book>
       <book available="5" id="4" tags="Harry">
           <title>Don</title>
           <author id="4">Manuel De Cervantes</author>
       </book>
   </books>
  </value>
</response>

I want to append a string value of my choosing to all attributes called "tags". This is whether the "tags" attribute has a value or not and also the attributes are at different levels of the xml structure. I have tried the method findall() but I keep on getting an error "IndexError: list index out of range." This is the code I have so far which is a little short but I have run out of steam for what else I need to type...

splitter = etree.XMLParser(strip_cdata=False)
xmldoc = etree.parse(os.path.join(root, xml_file), splitter ).getroot()
for child in xmldoc:
    if child.tag != 'response':
        allDescendants = list(etree.findall())
        for child in allDescendants:
            if hasattr(child, 'tags'):
                child.attribute["tags"].value = "someString"
0

1 Answer 1

1

findall() is the right API to use. Here is an example:

from lxml import etree
import os

splitter = etree.XMLParser(strip_cdata=False)
xml_file = 'foo.xml'
root = '.'
xmldoc = etree.parse(os.path.join(root, xml_file), splitter ).getroot()
for element in xmldoc.findall(".//*[@tags]"):
    element.attrib["tags"] += " KILROY!"

print etree.tostring(xmldoc)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.