0

I'd like to get some rows (z:row rows) from XML using:

<rs:data>
    <z:row Attribute1="1" Attribute2="1" />
    <z:row Attribute1="2" Attribute2="2" />
    <z:row Attribute1="3" Attribute2="3" />
    <z:row Attribute1="4" Attribute2="4" />
    <z:row Attribute1="5" Attribute2="5" />
    <z:row Attribute1="6" Attribute2="6" />
</rs:data>

I'm having trouble using (Python):

ElementTree.parse('myxmlfile.xml').getroot().findall('//z:row')

I think that two points are invalid in that case.

Anyone knows how can I do that?

2
  • XPathGet is a function? From what programming environment? Commented Jul 20, 2009 at 19:53
  • Consider XPathGet as a function that returns all nodes. Commented Jul 20, 2009 at 19:57

3 Answers 3

1

If I define the namespaces like this:

<?xml version="1.0"?>
<rs:data xmlns="http://example.com" xmlns:rs="http://example.com/rs" xmlns:z="http://example.com/z">
  <z:row Attribute1="1" Attribute2="1" />
  <z:row Attribute1="2" Attribute2="2" />
  <z:row Attribute1="3" Attribute2="3" />
  <z:row Attribute1="4" Attribute2="4" />
  <z:row Attribute1="5" Attribute2="5" />
  <z:row Attribute1="6" Attribute2="6" />
</rs:data>

the Python ElementTree-API can be used like this:

ElementTree.parse("r.xml").getroot().findall('{http://example.com/z}row')
# => [<Element {http://example.com/z}row at 551ee0>, <Element {http://example.com/z}row at 551c60>, <Element {http://example.com/z}row at 551f08>, <Element {http://example.com/z}row at 551be8>, <Element {http://example.com/z}row at 551eb8>, <Element {http://example.com/z}row at 551f30>]

See also http://effbot.org/zone/element.htm#xml-namespaces

Sign up to request clarification or add additional context in comments.

2 Comments

The lxml tutorial may be more helpful: codespeak.net/lxml/tutorial.html#namespaces
Just remember that "import lxml.etree" == "import xml.etree.ElementTree as etree" with a few exceptions.
1

If you don't want to figure out setting up namespaces properly, you can ignore them like this:

XPathGet("//*[local-name() = 'row']")

Which selects every node whose name (without namespace) is row.

Comments

1

The "z:" prefixes represent an XML namespace. you'll need to find out what that namespace is, and do the following:

XmlDocument doc = new XmlDocument();
doc.Load(@"File.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("z", @"http://thenamespace.com");
XmlNodeList nodes = doc.SelectNodes(@"//z:row", ns);

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.