Create new xml attributes from other attribute - python

I have the following XML
<icim source="source">
<object class="class_name" name="class_name">
<attribute name="Type">
<string>Type_Name</string>
</attribute>
<attribute name="DisplayName">
<string>DisplayName</string>
</attribute>
<attribute name="Vendor">
<string>Vendor_Name</string>
</attribute>
<attribute name="Model">
<string>Model_Name</string>
</attribute>
<attribute name="Description">
<string>Description_part1, Description_part2, Description_part3, Description_part4, Description_part5</string>
</attribute>
</object>
<object class="class_name" name="class_name">
<attribute name="Type">
<string>Type_Name</string>
</attribute>
<attribute name="DisplayName">
<DisplayName</string>
</attribute>
<attribute name="Vendor">
<string>Vendor_Name</string>
</attribute>
<attribute name="Model">
<string>Model_Name</string>
</attribute>
<attribute name="Description">
<string>Description_part1, Description_part2, Description_part3, Description_part4, Description_part5</string>
</attribute>
</object>
.
.
.
</icim>
and I want to transform it using Python's Element Tree to this:
<icim source="source">
<object class="class_name" name="class_name">
<attribute name="Type">
<string>Type_Name</string>
</attribute>
<attribute name="DisplayName">
<string>DisplayName</string>
</attribute>
<attribute name="Vendor">
<string>Vendor_Name</string>
</attribute>
<attribute name="Model">
<string>Model_Name</string>
</attribute>
<attribute name="String1">
<string>Description_part1</string>
</attribute>
</attribute>
<attribute name="String2">
<string>Description_part2</string>
</attribute>
</attribute>
<attribute name="String3">
<string>Description_part3</string>
</attribute>
<attribute name="Description">
<string>Description_part1, Description_part2, Description_part3, Description_part4, Description_part5</string>
</attribute>
</object>
<object class="class_name" name="class_name">
<attribute name="Type">
<string>Type_Name</string>
</attribute>
<attribute name="DisplayName">
<DisplayName</string>
</attribute>
<attribute name="Vendor">
<string>Vendor_Name</string>
</attribute>
<attribute name="Model">
<string>Model_Name</string>
</attribute>
</attribute>
<attribute name="String1">
<string>Description_part1</string>
</attribute>
</attribute>
<attribute name="String2">
<string>Description_part2</string>
</attribute>
</attribute>
<attribute name="String3">
<string>Description_part3</string>
</attribute>
<attribute name="Description">
<string>Description_part1, Description_part2, Description_part3, Description_part4, Description_part5</string>
</attribute>
</object>
.
.
.
</icim>
That is I want to extract the first three string parts from each Description element (the Description always has commas, so you can split the parts based on those) and create a new attribute for each of the first 3 Description parts. Thoughts?

Your xml and expected xml aren't well formed (<DisplayName</string> should be <string>DisplayName</string>) but assuming it's fixed, and if I undertstand you correctly, the following should get you at least most of the way there:
from lxml import etree
display = """[your xml above, corrected]"""
doc = etree.XML(display)
objs = doc.xpath("//object")
for obj in objs:
news = obj.xpath('.//attribute[# name="Description"]/string/text()')[0].split(',')[:3]
counter=3
for new in reversed(news): #this list needs to be reversed to get the new elements into the xml in the correct order
ins = etree.fromstring(f'<attribute name="String{counter}">\n <string>{new.strip()}</string>\n</attribute>\n')
obj.insert(4,ins)
counter-=1 #same reason for counting in reverse
print(etree.tostring(doc).decode())
Output should your expected output.

Related

Gtk3 - Python - Glade - 'Linked' comboboxes on different windows

I have two Gtk.Comboboxes on a main window :
the first, has its own Gtk.Liststore
the second one, linked to a Gtk.TreeModelFilter which is linked to a second Gtk.Liststore
When I select a value in the first one, the second one displays values according to my selection. This works well in the main window.
But in my application, I need to use this comboboxes combination many times, and when I use it on another window, this generates a Gtk Error that I don't understand:
"Gtk-CRITICAL **: 00:27:38.289:
gtk_tree_model_filter_set_visible_func: assertion
'filter->priv->visible_method_set == FALSE' failed"
Could someone explain me what's wrong with my code and what is the meaning of that error message?
Here is the glade file (test.ui)
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkListStore" id="liststore1">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">1</col>
<col id="1" translatable="yes">fruits</col>
</row>
<row>
<col id="0" translatable="yes">2</col>
<col id="1" translatable="yes">colors</col>
</row>
</data>
</object>
<object class="GtkListStore" id="liststore2">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">10</col>
<col id="1" translatable="yes">lemon</col>
</row>
<row>
<col id="0" translatable="yes">11</col>
<col id="1" translatable="yes">apple</col>
</row>
<row>
<col id="0" translatable="yes">12</col>
<col id="1" translatable="yes">strawberry</col>
</row>
<row>
<col id="0" translatable="yes">20</col>
<col id="1" translatable="yes">blue</col>
</row>
<row>
<col id="0" translatable="yes">21</col>
<col id="1" translatable="yes">yellow</col>
</row>
<row>
<col id="0" translatable="yes">22</col>
<col id="1" translatable="yes">purple</col>
</row>
</data>
</object>
<object class="GtkTreeModelFilter" id="filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="destroy" handler="on_quit" swapped="no"/>
<child>
<placeholder/>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">20</property>
<child>
<object class="GtkToolbar">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkToolButton">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Open other</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="on_other" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w1_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w1_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkDialog" id="window2">
<property name="can_focus">False</property>
<property name="type_hint">dialog</property>
<property name="transient_for">window1</property>
<child>
<placeholder/>
</child>
<child internal-child="vbox">
<object class="GtkBox">
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
<child internal-child="action_area">
<object class="GtkButtonBox">
<property name="can_focus">False</property>
<property name="layout_style">end</property>
<child>
<object class="GtkButton" id="btn_close">
<property name="label" translatable="yes">Close</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w2_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w2_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
<action-widgets>
<action-widget response="-7">btn_close</action-widget>
</action-widgets>
</object>
</interface>
and the python file (test.py):
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import sys
class Main:
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('test.ui')
self.builder.connect_signals(self)
self.obj = self.builder.get_object
self.window = self.obj('window1')
self.combo1 = self.obj('w1_combo1')
self.combo2 = self.obj('w1_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('filter')
self.filter.set_visible_func(self.filter_func)
self.combo1_val = None
self.window.show()
def on_other(self, btn):
Other(self.obj)
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
def on_quit(self, widget):
Gtk.main_quit()
class Other:
def __init__(self, obj):
self.obj = obj
self.window = self.obj('window2')
self.combo1 = self.obj('w2_combo1')
self.combo2 = self.obj('w2_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('filter')
self.filter.set_visible_func(self.filter_func)
self.btn_close = self.obj('btn_close')
self.btn_close.connect('clicked', self.on_hide)
self.combo1_val = None
self.window.show()
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
self.window.show()
def on_hide(self, btn):
self.window.hide()
def main():
app = Main()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())
Thank you in advance.
The problem was due to the fact that the second combobox on the main window and the second combobox on 'other' window were using the same filter.
I've created another filter and the second comboboxes have now their own filter linked to a common Gtk.Liststore.
Everything works fine, now.
Here are the corrected files :
The glade one :
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkListStore" id="liststore1">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">1</col>
<col id="1" translatable="yes">fruits</col>
</row>
<row>
<col id="0" translatable="yes">2</col>
<col id="1" translatable="yes">colors</col>
</row>
</data>
</object>
<object class="GtkListStore" id="liststore2">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">10</col>
<col id="1" translatable="yes">lemon</col>
</row>
<row>
<col id="0" translatable="yes">11</col>
<col id="1" translatable="yes">apple</col>
</row>
<row>
<col id="0" translatable="yes">12</col>
<col id="1" translatable="yes">strawberry</col>
</row>
<row>
<col id="0" translatable="yes">20</col>
<col id="1" translatable="yes">blue</col>
</row>
<row>
<col id="0" translatable="yes">21</col>
<col id="1" translatable="yes">yellow</col>
</row>
<row>
<col id="0" translatable="yes">22</col>
<col id="1" translatable="yes">purple</col>
</row>
</data>
</object>
<object class="GtkTreeModelFilter" id="w1_filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="destroy" handler="on_quit" swapped="no"/>
<child>
<placeholder/>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">20</property>
<child>
<object class="GtkToolbar">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkToolButton">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Open other</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="on_other" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w1_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w1_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">w1_filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkTreeModelFilter" id="w2_filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkDialog" id="window2">
<property name="can_focus">False</property>
<property name="type_hint">dialog</property>
<property name="transient_for">window1</property>
<child>
<placeholder/>
</child>
<child internal-child="vbox">
<object class="GtkBox">
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
<child internal-child="action_area">
<object class="GtkButtonBox">
<property name="can_focus">False</property>
<property name="layout_style">end</property>
<child>
<object class="GtkButton" id="btn_close">
<property name="label" translatable="yes">Close</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w2_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w2_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">w2_filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
<action-widgets>
<action-widget response="-7">btn_close</action-widget>
</action-widgets>
</object>
</interface>
And the python one :
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import sys
class Main:
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('test.ui')
self.builder.connect_signals(self)
self.obj = self.builder.get_object
self.window = self.obj('window1')
self.combo1 = self.obj('w1_combo1')
self.combo2 = self.obj('w1_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('w1_filter')
self.filter.set_visible_func(self.filter_func)
self.combo1_val = None
self.window.show()
def on_other(self, btn):
Other(self.obj)
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
#print(self.combo1_val, model[iter][0][:1])
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
def on_quit(self, widget):
Gtk.main_quit()
class Other:
def __init__(self, obj):
self.obj = obj
self.window = self.obj('window2')
self.combo1 = self.obj('w2_combo1')
self.combo2 = self.obj('w2_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('w2_filter')
self.filter.set_visible_func(self.filter_func)
self.btn_close = self.obj('btn_close')
self.btn_close.connect('clicked', self.on_hide)
self.combo1_val = None
self.window.show()
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
#print(self.combo1_val, model[iter][0][:1])
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
self.window.show()
def on_hide(self, btn):
self.window.hide()
def main():
app = Main()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())

Python - Read an XML using minidom

I'm new in Python and I have a question.
I'm trying to parse this xml (this XML has several information, this is the first data what I need to read):
<![CDATA[<?xml version="1.0" encoding="UTF-8"?><UDSObjectList>
<UDSObject>
<Handle>cr:908715</Handle>
<Attributes>
<Attribute DataType="2002">
<AttrName>ref_num</AttrName>
<AttrValue>497131</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>support_lev.sym</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="2004">
<AttrName>open_date</AttrName>
<AttrValue>1516290907</AttrValue>
</Attribute>
<Attribute DataType="58814636">
<AttrName>agt.id</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="2005">
<AttrName>priority</AttrName>
<AttrValue>3</AttrValue>
</Attribute>
<Attribute DataType="2009">
<AttrName>tenant.id</AttrName>
<AttrValue>F3CA8B5A2A456742B21EF8F3B5538623</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>tenant.name</AttrName>
<AttrValue>Ripley</AttrValue>
</Attribute>
<Attribute DataType="2005">
<AttrName>log_agent</AttrName>
<AttrValue>088966043F4D2944AA90067C52DA454F</AttrValue>
</Attribute>
<Attribute DataType="58826268">
<AttrName>request_by.first_name</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="58826268">
<AttrName>request_by.first_name</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="2002">
<AttrName>customer.first_name</AttrName>
<AttrValue>Juan Guillermo</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>customer.last_name</AttrName>
<AttrValue>Mendoza Montero</AttrValue>
</Attribute>
<Attribute DataType="2009">
<AttrName>customer.id</AttrName>
<AttrValue>8C020EBAD32035419D7654CDE510D312</AttrValue>
</Attribute>
<Attribute DataType="2001">
<AttrName>category.id</AttrName>
<AttrValue>1121021012</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>category.sym</AttrName>
<AttrValue>Ripley.Sistemas Financieros.Terminal Financiero.Mensaje de
Error</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>status.sym</AttrName>
<AttrValue>Suspended</AttrValue>
</Attribute>
<Attribute DataType="2009">
<AttrName>group.id</AttrName>
<AttrValue>099621F7BD77C545B65FB65BFE466550</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>group.last_name</AttrName>
<AttrValue>EUS_Zona V Region</AttrValue>
</Attribute>
<Attribute DataType="2001">
<AttrName>zreporting_met.id</AttrName>
<AttrValue>7300</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>zreporting_met.sym</AttrName>
<AttrValue>E-Mail</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>assignee.combo_name</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="2004">
<AttrName>open_date</AttrName>
<AttrValue>1516290907</AttrValue>
</Attribute>
<Attribute DataType="2004">
<AttrName>close_date</AttrName>
<AttrValue/>
</Attribute>
<Attribute DataType="2002">
<AttrName>description</AttrName>
<AttrValue>Asunto :Valaparaiso / Terminal Financiero Error
Nombre Completo :JUAN MENDOZA MONTERO
Ubicación :CCSS VALPARAISO Plaza victoria 1646, VALPARAISO
País :Chile
Telefono :ANEXO 2541
Correo :jmendozam#ripley.cl
Descripción :Error Terminal Financiero
Descartes :N/A</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>summary</AttrName>
<AttrValue>Santiago / Modificación </AttrValue>
</Attribute>
</Attributes>
</UDSObject>
but when I read the file with this method:
from zeep import Client
import xml.dom.minidom
from xml.dom.minidom import Node
def select():
resultado = []
sid = _client.service.login("User","password")
objectType = 'cr'
whereClause = "group.last_name LIKE 'EUS_ZONA%' AND open_date > 1517454000
AND open_date <
1519786800"
maxRows = -1
attributes = ["ref_num"
,"agt.id"
,"priority"
,"pcat.id"
,"tenant.id"
,"tenant.name"
,"log_agent"
,"request_by.first_name"
,"request_by.last_name"
,"customer.first_name"
,"customer.last_name"
,"customer.id"
,"category.id"
,"category.sym"
,"status.sym"
,"group.id"
,"group.last_name"
,"zreporting_met.id"
,"zreporting_met.sym"
,"assignee.combo_name"
,"open_date"
,"close_date"
,"description"
,"summary"]
minim = _client.service.doSelect(sid=sid, objectType=objectType,
whereClause=whereClause, maxRows= maxRows, attributes= attributes)
dom = xml.dom.minidom.parseString(minim)
nodeList = dom.getElementsByTagName('AttrValue')
for j in range(len(nodeList)):
resultado.append(dom.getElementsByTagName('AttrValue')[j].firstChild.wholeText)
print(resultado[j])
logout = _client.service.logout(sid)
This only print the first AttrValue (ref_num value), what I need to do is add every field of the XML file in resultado array, I need help to print every field from the XML file, someone can help me to that?
Please read and follow How to create a Minimal, Complete, and Verifiable example.
You should remove all the server stuff and reduce the size of your sample data.
This snippet follows your code and gets all attribute elements and then iterates those:
import xml.dom.minidom
from xml.dom.minidom import Node
minim = """<?xml version="1.0" encoding="UTF-8"?>
<udsobjectlist>
<udsobject>
<handle>cr:908715</handle>
<attributes>
<attribute datatype="2002">
<attrname>ref_num</attrname>
<attrvalue>497131</attrvalue>
</attribute>
<attribute datatype="2002">
<attrname>support_lev.sym</attrname>
<attrvalue/>
</attribute>
<attribute datatype="2004">
<attrname>open_date</attrname>
<attrvalue>1516290907</attrvalue>
</attribute>
</attributes>
</udsobject>
</udsobjectlist>
"""
dom = xml.dom.minidom.parseString(minim)
nodeList = dom.getElementsByTagName('attribute')
resultado = []
attributes = ["attrname", "attrvalue"]
for node in nodeList:
a = []
for attribute in attributes:
try:
a.append( node.getElementsByTagName(attribute)[0].firstChild.wholeText)
except AttributeError:
a.append("")
resultado.append(a)
print(resultado)
prints
[['ref_num', '497131'], ['support_lev.sym', ''], ['open_date', '1516290907']]
Even closer to your code:
nodeList = dom.getElementsByTagName('attrvalue')
for node in nodeList:
try:
v = node.firstChild.wholeText
resultado.append(v)
print(v)
except:
pass
print(resultado)
prints
497131
1516290907
['497131', '1516290907']
As suggested in the comments, with ET (although you probably should not access elements by index, but this might get you started):
import xml.etree.ElementTree as ET
root = ET.fromstring(minim)
for child in root[0][1]:
try:
print(child[0].text)
print(child[1].text)
except:
pass
prints
ref_num
497131
support_lev.sym
None
open_date
1516290907

How to remove only the parent element and not its child elements in Python?

A similar question to the one in JavaScript
I have a xml and want to comment just the parent tag without its children
like in the example below:
<object id="12">
<process name="Developer">
<appdef>
<attributes>
<attribute name="X">
<ProcessValue datatype="number" value="15" />
</attribute>
<attribute name="Y">
<ProcessValue datatype="number" value="59" />
</attribute>
</attributes>
</appdef>
</process>
</object>
and comment just < object > tags
<!--<object id="12">-->
<process name="Developer">
<appdef>
<attributes>
<attribute name="X">
<ProcessValue datatype="number" value="15" />
</attribute>
<attribute name="Y">
<ProcessValue datatype="number" value="59" />
</attribute>
</attributes>
</appdef>
</process>
<!--</object>-->
I have a code to comment the tag but it comment all its children also.
Thank you very much I appreciate any help
Due to confusions I am attaching the whole code:
from xml.dom import minidom
xml = """\
<bpr:release xmlns:bpr="http://www.blueprism.co.uk/product/release">
<object id="0e694daf-836e-44a9-816a-9b8127abb7b2" name="Developer 2
ex" xmlns="http://www.blueprism.co.uk/product/process">
<process name="Developer 2 ex" version="1.0" bpversion="5.0.33.0"
narrative="BO for automation the HTML page
" type="object"
runmode="Exclusive">
<appdef>
<attributes>
<attribute name="X">
<ProcessValue datatype="number" value="15" />
</attribute>
<attribute name="Y">
<ProcessValue datatype="number" value="59" />
</attribute>
</attributes>
</appdef>
</process>
</object>
</bpr:release>
"""
def comment_node(node):
comment = node.ownerDocument.createComment(node.toxml())
print(comment)
node.parentNode.replaceChild(comment, node)
return comment
doc = minidom.parseString(xml).documentElement
comment_node(doc.getElementsByTagName('object')[-1])
xml = doc.toxml()

Parse XML with Python with title and value on different lines

I have the following XML document that i would like to write to a csv file.
<items>
<item>
<attribute type="set" identifier="naadloos">
<name locale="nl_NL">Naadloos</name>
<value locale="nl_NL" identifier="nee">Nee</value>
</attribute>
<attribute type="asset" identifier="short_description">
<value locale="nl_NL">Tom beugel bh</value>
</attribute>
<attribute type="text" identifier="name">
<name locale="nl_NL">Naam</name>
<value>Marie Jo L'Aventure Tom beugel bh</value>
</attribute>
<attribute type="int" identifier="is_backorder">
<name locale="nl_NL">Backorder</name>
<value>2</value>
</attribute>
</item>
</items>
how can i retrieve the data from this format? I need the following output
naadloos, short_description, name, is_Backorder
Nee, Tom beugel bh, Marie Jo L'Adventure Tom beugel bh, 2
so i need the identifier from the attribute line, and the text from the value line.
Any ideas?
Much appreciated
This is my try it gets elements by attribute and writes them into a specified file by dictwriter!
import lxml.etree as et
import csv
#headers={}
xml= """<items>
<item>
<attribute type="set" identifier="naadloos">
<name locale="nl_NL">Naadloos</name>
<value locale="nl_NL" identifier="nee">Nee</value>
</attribute>
<attribute type="asset" identifier="short_description">
<value locale="nl_NL">Tom beugel bh</value>
</attribute>
<attribute type="text" identifier="name">
<name locale="nl_NL">Naam</name>
<value>Marie Jo L'Aventure Tom beugel bh</value>
</attribute>
<attribute type="int" identifier="is_backorder">
<name locale="nl_NL">Backorder</name>
<value>2</value>
</attribute>
</item>
</items>
"""
tree = et.fromstring(xml)
header = []
for i in tree.xpath("//attribute/#identifier"):
header.append(i)
def dicter(x):
exp = r"//attribute[#identifier='%s']/value/text()"%x
tmp = ''.join(tree.xpath(exp))
d = [x,tmp]
return d
data = dict(dicter(i) for i in header)
#Now write data into file
with open(r"C:\Users\User_Name\Desktop\output.txt",'wb') as wrt:
writer = csv.DictWriter(wrt,header)
writer.writeheader()
writer.writerow(data)
Written file content-
naadloos,short_description,name,is_backorder
Nee,Tom beugel bh,Marie Jo L'Aventure Tom beugel bh,2

Python XRC Buttons not clickable

I'm working on a python app, and have hit a snag. My goal is to have a main frame containing numerous controls, and a panel which will be loaded from an xrc file specified at run time. Essentially, when a user clicks a button, I want a panel to be populated from an xrc file, the xrc file is chosen based on which button is clicked.
I'm defining the UI with XRCed, and here's what I have so far. This seems to load the sub-panel controls into the frame, but they aren't clickable, and they don't appear within the DynamicPanel as I hoped they would. Your help would be greatly appreciated.
EDIT
I've revised my main code, and now the controls appear where they in the frame, however the buttons still aren't clickable. Can anyone tell me why?
Python code:
import wx
import wx.xrc as xrc
from UNTITLED_xrc import xrcFRAME1
class XrcFrameSubClass(xrcFRAME1):
""""""
#----------------------------------------------------------------------
def __init__(self):
xrcFRAME1.__init__(self, parent = None)
self.Bind(wx.EVT_BUTTON, self.OnButton_1, self.button1)
self.Bind(wx.EVT_BUTTON, self.OnButton_2, self.button2)
self.Bind(wx.EVT_BUTTON, self.OnButton_Clear, self.Button_Clear)
self.Show()
def OnButton_Clear(self, event):
self.ClearSubPanel()
def ClearSubPanel(self):
try:
self.SubPanel.Destroy()
self.Fit()
self.Layout()
except:
pass
def OnButton_1(self, event):
self.ClearSubPanel()
SubPanel_xrc = '''<?xml version="1.0" ?><resource>
<object class="wxPanel" name="SubPanel">
<object class="wxBoxSizer">
<orient>wxVERTICAL</orient>
<object class="sizeritem">
<object class="wxStaticText">
<label>Your Mother was a</label>
</object>
</object>
<object class="sizeritem">
<object class="wxButton" name="SubButton1">
<label>Hamster</label>
</object>
</object>
<object class="sizeritem">
<object class="wxButton" name="SubButton2">
<label>Black Knight</label>
</object>
</object>
</object>
</object>
</resource>'''
#PanelCoord = self.DynamicPanel.GetPosition()
TopSizer = self.TopPanel.GetSizer()
res = xrc.EmptyXmlResource() #Here it is
res.LoadFromString(SubPanel_xrc)
self.SubPanel = res.LoadPanel(self, "SubPanel")
#Note: the first argument of the sizer.Insert() method is the index at which to insert the new item
TopSizer.Insert(1,self.SubPanel,1, wx.EXPAND|wx.ALL, 5)
self.Fit()
self.Layout()
# #Not sure how to do the event binding dynamically yet
# self.SubButton1 = xrc.XRCCTRL(self.SubPanel, "SubButton1")
# self.SubButton2 = xrc.XRCCTRL(self.SubPanel, "SubButton2")
def OnButton_2(self, event):
self.ClearSubPanel()
SubPanel_xrc = '''<?xml version="1.0" ?>
<resource>
<object class="wxPanel" name="SubPanel">
<object class="wxBoxSizer">
<orient>wxHORIZONTAL</orient>
<object class="sizeritem">
<object class="wxStaticText">
<label>Your father smelt of</label>
</object>
</object>
<object class="sizeritem">
<object class="wxButton" name="SubButton1">
<label>Elderberries</label>
</object>
</object>
<object class="sizeritem">
<object class="wxButton" name="SubButton2">
<label>Shrubberies</label>
</object>
</object>
</object>
</object>
</resource>'''
TopSizer = self.TopPanel.GetSizer()
res = xrc.EmptyXmlResource() #Here it is
res.LoadFromString(SubPanel_xrc)
self.SubPanel = res.LoadPanel(self, "SubPanel")
#Note: the first argument of the sizer.Insert() method is the index at which to insert the new item
TopSizer.Insert(1,self.SubPanel,1, wx.EXPAND|wx.ALL, 5)
self.Layout()
self.Fit()
# self.SubButton1 = xrc.XRCCTRL(self.SubPanel, "SubButton1")
# self.SubButton2 = xrc.XRCCTRL(self.SubPanel, "SubButton2")
if __name__ == "__main__":
app = wx.App(False)
frame = XrcFrameSubClass()
app.MainLoop()
MainFrame:
<?xml version="1.0" encoding="cp1252"?>
<resource>
<object class="wxFrame" name="FRAME1">
<title>This is the title</title>
<object class="wxPanel" name="TopPanel">
<object class="wxBoxSizer">
<orient>wxVERTICAL</orient>
<object class="sizeritem">
<object class="wxBoxSizer">
<orient>wxVERTICAL</orient>
<object class="sizeritem">
<object class="wxButton" name="button1">
<label>Load SubXRC 1</label>
</object>
<option>1</option>
<flag>wxGROW</flag>
</object>
<object class="sizeritem">
<object class="wxButton" name="button2">
<label>Load SubXRC 2</label>
</object>
<option>1</option>
<flag>wxGROW</flag>
</object>
<object class="sizeritem">
<object class="wxButton" name="Button_Clear">
<label>Clear</label>
</object>
</object>
<object class="spacer">
<size>40,20</size>
</object>
</object>
</object>
<object class="sizeritem">
<object class="wxPanel" name="DynamicPanel"/>
<option>1</option>
<flag>wxEXPAND</flag>
<minsize>100,200</minsize>
</object>
<object class="sizeritem">
<object class="wxBoxSizer">
<orient>wxHORIZONTAL</orient>
<object class="sizeritem">
<object class="wxButton" name="button3">
<label>button3</label>
</object>
</object>
<object class="sizeritem">
<object class="wxButton" name="button4">
<label>button4</label>
</object>
</object>
</object>
<flag>wxALIGN_CENTRE</flag>
</object>
</object>
</object>
</object>
</resource>

Categories

Resources