XML шаблон

есьт файл blist.xml
oit-note .purple # cat blist.xml

<?xml version="1.0" ?><purple version="1.0">
        <blist>

        <group name="Отдел ИТ">
                        <setting name="collapsed" type="bool">0</setting>
                        <contact>
                                <buddy account="user1@server/" proto="prpl-jabber">
                                        <name>user1@server</name>
                                        <alias>Иванов Иван</alias>
                                        <setting name="last_seen" type="int">1390552465</setting>
                                </buddy>
                        </contact>

                </group></blist>
        <privacy>
                <account mode="1" name="ahmetov_ag@cds.nchkz.local/" proto="prpl-jabber"/>
        </privacy>
</purple>

и есть шаблон, который я хочу применить к этому файлу, что добавить в pidgin общий чат всем пользователям:

cds .purple # cat blist.xml

 # Calculate format=xml_gconf
<?xml version='1.0' encoding='UTF-8' ?>

<purple version='1.0'>
<blist>

<group name='Чаты'>
        <setting name='collapsed' type='bool'>0</setting>
        <chat proto='prpl-jabber' account='#-ur_jid-#/'>
                <alias>Общий чат</alias>
                <component name='server'>conference.cds.server.local</component>
                <component name='room'>чат</component>
                <setting name='gtk-persistent' type='bool'>1</setting>
                <setting name='gtk-mute-sound' type='bool'>0</setting>
                <setting name='gtk-autojoin' type='bool'>1</setting>
        </chat>
</group>

</blist>
</purple>

только почему то этот шаблон не работает :frowning: подскажите где я ошибаюсь?

Вам придется делать исполняемый шаблон, который будит парсить xml-файл и добавлять нужные данные, т.к. реализована поддержка формата xml-конфигов лишь для некоторых программ.

Пример можете посмотреть в шаблоне - <</var/lib/layman/calculate/profiles/templates/3.1/6_ac_desktop_profile/2-user/net-im/pidgin-always/sortblist.py>>

Он оперирует именно этим файлом и выполняет алфавитную сортировку групп в контакт-листе.

спасибо! буду делать посмотреть)

Если вдруг споткнетесь при парсинге, что вам понадобится ссылка на элемент-родитель, то здесь описано как это реализовать.

Если кому-то нужно вот, написал немного, может кому нибудь пригодится.
Шаблон добавляет всем пользователям джабера (pidgin) группу Чаты и чат all-chat. Строго не судите, первый опыт… Зато все работает, у меня по-крайней мере…

Еще вопрос есть - сначала сервер jabber у меня назывался допустим cds.example.com и в переменной #-ur_jid-# у пользователя была запись user@cds.example.com. сейчас я в конфиге джабера исправил на example.ru. а переменная #-ur_jid-# осталась прежней, это как то можно изменить?

#Calculate exec=/usr/bin/python path=/tmp name=addchat2blist_#-ur_login-#.py
#!/usr/bin/python
#*- coding: utf-8 -*-

import os,sys
from lxml import etree

myGroupName = u'Чаты'
myChatName = u'Общий чат'
myChatRoom = u'all-chat'
userName = '''#-ur_login-#'''
#jabberAccount = '''#-ur_jid-#'''
jabberAccount = "%s@example.com" % userName
jabberServer = 'example.com'
parser = etree.XMLParser(remove_blank_text=True)

try:
    homedir = "#-ur_home_path-#"
    blistfile="/.purple/blist.xml"

    if os.path.exists(homedir+blistfile) :
        #Buddy list file opening and get groups-list
        blist=etree.parse(homedir+blistfile, parser).getroot()
        elements=blist.findall("./blist/group")
        #blist.findall("./blist/group[@name='asd']")

        #Группа Чаты может быть только одна
        matchingNodes = [node for node in elements if node.attrib['name'] == myGroupName]
        if len(matchingNodes) == 1:
          print "Группа %s уже существует" % myGroupName.encode('utf-8')
          groupIndex = blist[0].index([node for node in elements if node.attrib['name'] == myGroupName][0])                                                                                                                                  
          isGroupExists = True                                                                                                                                                                                                               
          #Список чатов в группе Чаты                                                                                                                                                                                                        
          chats = blist.findall("./blist/group/chat/alias")                                                                                                                                                                                  
          #Ищем, существует ли добавляемый чат                                                                                                                                                                                               
          mychat = [node for node in chats if node.text == myChatName]                                                                                                                                                                       
          if len(mychat) == 1:                                                                                                                                                                                                               
            print "Чат уже добавлен, ничего не делаем, выходим"                                                                                                                                                                              
            exit(0)                                                                                                                                                                                                                          
          else:                                                                                                                                                                                                                              
            print "Добавляем чат в существующую группу"                                                                                                                                                                                      
            #chat                                                                                                                                                                                                                            
            childChat = (etree.Element('chat', account=jabberAccount+'/', proto="prpl-jabber"))                                                                                                                                              
            #alias                                                                                                                                                                                                                           
            childAlias = (etree.Element('alias'))                                                                                                                                                                                            
            childAlias.text = myChatName                                                                                                                                                                                                     
            childChat.append(childAlias)                                                                                                                                                                                                     
            #component                                                                                                                                                                                                                       
            childComp1 = (etree.Element('component', name="server"))                                                                                                                                                                         
            childComp1.text = 'conference.'+jabberServer
            childChat.append(childComp1)
            childComp2 = (etree.Element('component', name="room"))
            childComp2.text = myChatRoom
            childChat.append(childComp2)
            childComp3 = (etree.Element('component', name="handle"))
            childComp3.text = userName
            childChat.append(childComp3)
            #setting
            childSetting1 = (etree.Element('setting', name="gtk-persistent", type="bool"))
            childSetting1.text = "1"
            childChat.append(childSetting1)
            childSetting2 = (etree.Element('setting', name="gtk-mute-sound", type="bool"))
            childSetting2.text = "0"
            childChat.append(childSetting2)
            childSetting3 = (etree.Element('setting', name="gtk-autojoin", type="bool"))
            childSetting3.text = "1"
            childChat.append(childSetting3)
            blist[0][groupIndex].append(childChat)
            #Добаляю новую группу в blist
            blist[0][1].insert(groupIndex, childChat)

        else:
          print "Группа %s не существует, нужно добавить" % myGroupName.encode('utf-8')
          isGroupExists = False

          group = etree.Element('group', name=myGroupName)
          #setting
          childSetting = (etree.Element('setting', name="collapsed", type="bool"))
          childSetting.text="0"
          group.append(childSetting)
          #chat
          childChat = (etree.Element('chat', account=jabberAccount+'/', proto="prpl-jabber"))
          #alias
          childAlias = (etree.Element('alias'))
          childAlias.text = myChatName
          childChat.append(childAlias)
          #component
          childComp1 = (etree.Element('component', name="server"))
          childComp1.text = 'conference.'+jabberServer
          childChat.append(childComp1)
          childComp2 = (etree.Element('component', name="room"))
          childComp2.text = myChatRoom
          childChat.append(childComp2)
          childComp3 = (etree.Element('component', name="handle"))
          childComp3.text = userName
          childChat.append(childComp3)
          #setting
          childSetting1 = (etree.Element('setting', name="gtk-persistent", type="bool"))
          childSetting1.text = "1"
          childChat.append(childSetting1)
          childSetting2 = (etree.Element('setting', name="gtk-mute-sound", type="bool"))
          childSetting2.text = "0"
          childChat.append(childSetting2)
          childSetting3 = (etree.Element('setting', name="gtk-autojoin", type="bool"))
          childSetting3.text = "1"
          childChat.append(childSetting3)

          group.append(childChat)
          #Добаляю новую группу в blist
          blist[0].insert(0, group)

        #Write to Buddy list file
        blistout=open(homedir+blistfile,"w")
        blistout.write(etree.tostring(blist, pretty_print=True, encoding='utf-8', xml_declaration=True))
        blistout.close()
except Exception as e:
    sys.stderr.write(str(e))