简体   繁体   中英

Changing XML using LXML and Python

I have a XML file "definitions.xml" with below content.

<Definitions>
  <Process name="en">
    <property name="am">OLD_A</property>
    <property name="24hours" xsi:type="xsd:boolean">OLD_B</property>
  </Process>
</Definitions>

I want to modify the file as below:

<Definitions>
  <Process name="en">
    <property name="am">NEW_A</property>
    <property name="24hours" xsi:type="xsd:boolean">NEW_B</property>
  </Process>
</Definitions>

I have tried below code:

from lxml import etree

def Definations_Parser():
 global Definations_tree
 global Definations_root
 parser =  etree.XMLParser(remove_blank_text = True)
 Definations_tree = etree.parse('C:\\Users\\dell\\Desktop\\definitions.xml', parser)
 Definations_root = Definations_tree.getroot()

def Definations_File_Modify():
    Process_1 = Definations_root.find('Process')
    property_1 = Process_1.find('property[@name="am"]')
    print ('Current value is:', property_1.get('name'))

def Definations_File_Write():
 Definations_tree.write('C:\\Users\\dell\\Desktop\\definitions.xml', pretty_print = True)

Definations_Parser()
Definations_File_Modify()
Definations_File_Write()

How can I get current present values "OLD_A" and "OLD_B" and change it to "NEW_A" and "NEW_B" ?

Like @tangoal mentioned in the comments, you use the text property of the element like so:

from lxml import etree

def Definations_Parser():
    global Definations_tree
    global Definations_root
    parser =  etree.XMLParser(remove_blank_text = True)
    Definations_tree = etree.parse('C:\\Users\\dell\\Desktop\\definitions.xml', parser)
    Definations_root = Definations_tree.getroot()

def Definations_File_Modify():
    Process_1 = Definations_root.find('Process')
    property_1 = Process_1.find('property[@name="am"]')
    print(property_1.text)
    property_1.text = 'NEW_A'
    print(property_1.text)

    property_2 = Process_1.find('property[@name="24hours"]')
    print(property_2.text)
    property_2.text = 'NEW_B'
    print(property_2.text)

def Definations_File_Write():
    Definations_tree.write('C:\\Users\\dell\\Desktop\\definitions.xml', pretty_print = True)

Definations_Parser()
Definations_File_Modify()
Definations_File_Write()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM