I have an xml string that looks something like this:
I am using the Element Tree library
<?xml version="1.0" encoding="UTF-8"?>
<GetCategoriesResponse xmlns="urn:ebay:apis:eBLBaseComponents"><CategoryArray><Category><WantedParm1>true</WantedParm1><UnwantedParm1>true</UnwantedParm1><WantedParm2>20081</WantedParm2></Category></CategoryArray></GetCategoriesResponse>
I want to get some values of the Category Node, let's call them Wanted Parms 1 and 2. However I am getting an AttributeError probably because the code I wrote is not able to find the child node of the Category item.
AttributeError: 'NoneType' object has no attribute 'text'.
import xml.etree.ElementTree as ET
XML = #Above Code in String
tree = ET.ElementTree(ET.fromstring(XML))
root = tree.getroot()
for Category in root[0]:
one = Category.find("WantedParm1").text
two = Category.find("WantedParm2").text
print(one, two)
-
Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your code and accurately describe the problem. "Having issues" is not a problem description.Prune– Prune2016年10月26日 00:43:30 +00:00Commented Oct 26, 2016 at 0:43
-
@Prune I am really sorry, I pressed submit while typing the question and it uploaded the form. I'm trying to update it asapJuanvulcano– Juanvulcano2016年10月26日 00:44:22 +00:00Commented Oct 26, 2016 at 0:44
-
Understood. However, you still haven't posted a MCVE so we can reproduce the problem. Your call to find has returned None, but that's about as far as I can take you at this point -- in short, what you already suspected.Prune– Prune2016年10月26日 00:48:08 +00:00Commented Oct 26, 2016 at 0:48
-
@Prune This is pretty much all the code that interacts. What other information would you like to have?Juanvulcano– Juanvulcano2016年10月26日 00:57:06 +00:00Commented Oct 26, 2016 at 0:57
-
Cut-and-paste code that reproduces the problem. I've wrapped the XML structure in triple quotation marks and run the program, but the error I get is a parse failure in fromstring: xml.parsers.expat.ExpatError: mismatched tag: line 6, column 29, which appears to be the start of </WantedParm1>Prune– Prune2016年10月26日 01:08:57 +00:00Commented Oct 26, 2016 at 1:08
1 Answer 1
The XML elements are in the default namespace urn:ebay:apis:eBLBaseComponents So all tags get prepended with the full URI of the namespace.
Changing your find() parameter to include the URI should work.
import xml.etree.ElementTree as ET
XML = #Above Code in String
tree = ET.ElementTree(ET.fromstring(XML))
root = tree.getroot()
for Category in root[0]:
one = Category.find("{urn:ebay:apis:eBLBaseComponents}WantedParm1").text
two = Category.find("{urn:ebay:apis:eBLBaseComponents}WantedParm2").text
print(one, two)
You can find more information on dealing with namespaces on the element tree docs here or this stack overflow post.