Simple processing of xml files in python

If Python wants to read some information from xml, it may be easier to use BeautifulSoup, but if you want to modify xml, BeautifulSoup will not be able to do it, in fact, just use lxml directly.

1 from lxml import etree
2 
3 tree = etree.parse("xxx.xml")
4 cfgs = tree.find('//component[@name="cmake-settings"]/configurations')
5 cfgs.clear()
6 cfgs.append(etree.Element("configuration", attrib={"CONFIG_NAME":"Debug"}))
7 tree.write("xxx.xml")

 etree represents the entire xml tree structure, and the modification of its elements is directly manifested as the modification of etree, and then it can be stored. The general function usage can be checked now, only XPath needs to be understood. At present, I only know the following items, which are basically sufficient:

  • /: Indicates similar to / in the path, indicating the next level
  • //: Indicates descendants, that is, the next level, the next two levels, and so on...
  • [@<attr-name>=<attr-val>]: can filter by attribute value
  • *: means match all, for example: //* means all descendants

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324818173&siteId=291194637