473,246 Members | 1,309 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,246 software developers and data experts.

insert method in ElementTree

O/S: Win2K
Vsn of Python: 2.4

Example:

<a>
<b createAnotherWhenCondition="x">
<c>text for c</c>
<d>text for d</d>
</b>
<e>
<f>text for f</f>
<g>text for g</g>>
</e>
<h>
<i>text for i</i>
<j createAnotherWhenCondition="y">
<k>text for k</k>
<l>text for l</l>
</j>
<m>text for m</m>
</h>
</a>

Python script reads XML document above into ElementTree. The script
outputs an XML document that is based on the XML document above. The
output XML will contain all of the elements in the XML document above.
If there is a parent element that does not have the
createAnotherWhencondition attribute, then that element and its
descendants will be part of the output XML. If there is a parent
element with atribute createAnotherWhenCondition and that condition is
true, then the output XML should contain another instance of the parent
element below the original instance. For example if x were true when
the script ran, the output XML document would be:

<a>
<b>
<c>text for c</c>
<d>text for d</d>
</b>
<b>
<c>text for c</c>
<d>text for d</d>
</b>
<e>
<f>text for f</f>
<g>text for g</g>>
</e>
<h>
<i>text for i</i>
<j>
<k>text for k</k>
<l>text for l</l>
</j>
<m>text for m></m>
</h>
</a>

The example attempts to illustrate that the createAnotherWhenCondition
attribute may appear in parent elements that are at different levels in
the hierarchy; the <belement is at the 2nd level in the hierarchy,
and the <jelement is at the 3rd level. There will never be
'nesting', i.e. a parent element with the
createAnotherWhenCondition attribute that is a descendant of a parent
element with a createAnotherWhenCondition attribute.

I'm pretty sure I can figure out how to create the output XML by
creating a second XML document. It would be created by iterating
through the input XML. When a new element is encountered, an element
or subelement would be created in the output XML. When a parent
element with the createAnotherWhenCondition is encountered and that
condition is true, I think I can figure out how to propagate another
instance of that parent element and all its descendants.

My request for advice is this: instead of creating a second XML
document that represents the output, would it be possible to expand the
input XML document as needed? I was thinking that the program could
iterate through all the elements. As it is iterating, it would check
for the createAnotherWhenCondition attribute. If encountered and if
the condition were true, the program would:
- make a copy of the parent element (perhaps with copy.copy)
- use the insert method to insert the just-created copy
Where I'm struggling is figuring out what the index argument should
be in the insert method. Using the example above

# assume rootElement is the root of the input XML
xList = rootElement.getiterator()
idx = 0
for x in xList:
# mix of pseudo-code and Python code
if (this element has createAnotherWhenCondition attribute)
and
(y is true):
jcopy = copy.copy(x)
??.insert(??, jcopy)
idx = idx + 1

If the program were run when y was true, then I believe it would
encounter the <jelement when idx has a value of 9. Conceptually, I
think that jcopy should be inserted after the <jelement and before
the <melement. But I'm not sure that 9 (the index in the list
created from rootElement.getiterator()) has any relevance for this
insert task. Assuming that I want to insert jcopy after the <j>
element and before the <melement:
a) would the insert need to be done relative to the <helement, which
is the parent of <j>
b) if so, would the index argument in the insert method be relative
index within the <helement?

Jul 16 '06 #1
2 4150
mi************@yahoo.com wrote:
Where I'm struggling is figuring out what the index argument should
be in the insert method. Using the example above

# assume rootElement is the root of the input XML
xList = rootElement.getiterator()
idx = 0
for x in xList:
# mix of pseudo-code and Python code
if (this element has createAnotherWhenCondition attribute)
and
(y is true):
jcopy = copy.copy(x)
??.insert(??, jcopy)
idx = idx + 1
ElementTree does not have parent pointers. You have to look one element level
ahead to add the child. You can use a parent stack for this, although
getiterator() is not very helpful in that case as it does not tell you when it
backtracks.

If you want to use lxml instead, you can either
* access the parent directly (element.getparent()) and add the child there
or
* use the iterwalk() function to add the child when backtracking up the tree or
* implement the whole thing in XSLT (with a custom evaluator function in Python).

There may also be other ways to do it. Just give it a try:
http://codespeak.net/lxml/
http://cheeseshop.python.org/pypi/lxml/1.1alpha

Stefan
Jul 16 '06 #2
mi************@yahoo.com wrote:
My request for advice is this: instead of creating a second XML
document that represents the output, would it be possible to expand the
input XML document as needed? I was thinking that the program could
iterate through all the elements. As it is iterating, it would check
for the createAnotherWhenCondition attribute. If encountered and if
the condition were true, the program would:
- make a copy of the parent element (perhaps with copy.copy)
- use the insert method to insert the just-created copy
Where I'm struggling is figuring out what the index argument should
be in the insert method.
I recommend not using the insert method; instead, build a new list of
elements and set the parent to the new list. Another problem is that
you have to have the parent node around, since children don't indicate
their parents. Using getiterator won't work. I recommend a recursive
function instead. Something like this should do it:

def expand_children(parent):
if len(parent) == 0:
return
newchildren = []
for child in parent:
expand_children(child) # recursively process child nodes
if <you're supposed to create another child>:
<remove createAnotherWhenCondition attr>
newchildren.append(child) # or copy.copy(child)
newchildren.append(child)
parent[:] = newchildren # slice assign

So, basically, for each node, you build a list of children in parallel,
making duplicates as necessary, then use slice assignment to set the
parent's children to be the new list. No more mucking around with
indexes.
Carl Banks

Jul 16 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Stewart Midwinter | last post by:
I want to parse a file with ElementTree. My file has the following format: <!-- file population.xml --> <?xml version='1.0' encoding='utf-8'?> <population> <person><name="joe" sex="male"...
1
by: Greg Wilson | last post by:
I'm trying to convert from minidom to ElementTree for handling XML, and am having trouble with entities in DTDs. My Python script looks like this: ...
1
by: mirandacascade | last post by:
I do not understand how to use the find() method in ElementTree. The file 'sample.xml' is: <?xml version="1.0"?> <SampleRoot> <Header> <Product>FindMystery</Product> </Header>...
3
by: mirandacascade | last post by:
Verion of Python: 2.4 O/S: Windows XP ElementTree resides in the c:\python24\lib\site-packages\elementtree\ folder When a string that does not contain well-formed XML is passed as an argument...
1
by: mirandacascade | last post by:
O/S: Windows 2K Vsn of Python: 2.4 Currently: 1) Folder structure: \workarea\ <- ElementTree files reside here \xml\ \dom\
15
by: Steven Bethard | last post by:
I'm having trouble using elementtree with an XML file that has some gbk-encoded text. (I can't read Chinese, so I'm taking their word for it that it's gbk-encoded.) I always have trouble with...
0
by: Greg Aumann | last post by:
I am trying to write some python code for a library that reads an XML-like language from a file into elementtree data structures. Then I want to be able to read and/or modify the structure and then...
0
by: Tim Arnold | last post by:
Hi, I'm using the TidyHTMLTreeBuilder to generate some elementtrees from html. One by-product is that I'm losing comments embedded in the html. So I'm trying to put them back in, but I'm doing...
3
by: gray.bowman | last post by:
I'm messing around with trying to write an xml file using xml.etree.ElementTree. All the examples on the internet show the use of ElementTree.write(), although when I try to use it it's not...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.