[Python applet] Use lxml to modify the XML file and traverse the directory

Source: Internet
Author: User
Tags xpath

The purpose of this time is to traverse the directory and update the target file and the corresponding directory information to the XML file. After painful groping, the elementtree from Python comes to lxml. The reason for abandoning the elementtree is that namespace.

XML namespaces

The role is to avoid element naming conflicts, and when naming conflicts occur, prefixes can be used to avoid naming conflicts, such as:

<h:table>    <H:tr>    <H:TD>APP Store</H:TD>    <H:TD>Google Play</H:TD>    </H:tr></h:table>

Using Namespaces (namespaces):

<f:tablexmlns:f= "Http://www.w3school.com.cn/furniture">   <F:name>African Coffee Table</F:name>   <F:width>80</F:width>   <F:length>120</F:length></f:table>

The xmlns attribute added gives a qualified name associated with a namespace for the prefix

lxml Installation:
    1. Install PIP
    2. Installing Setuptools:windows (POWERSHELL3) input
      > (invoke-webrequest https://bootstrap.pypa.io/ez_setup.py). Content | Python-

    3. Download LXML.WHL, select the appropriate WHL download according to the Python version: Address
    4. Installing Wheel
      Pip Install Wheel

    5. Install the downloaded WHL file
      Pip install. \LXML-3.5.0-CP34-NONE-WIN_AMD64.WHL

lxml using:

lxml's tutorial site is: http://lxml.de/index.html

Use lxml to import this:

 from Import etree

To import and parse an XML file:

Tree = Etree.parse (fileName)

Gets the namespace of the XML:

root = Tree.getroot () Nsmap = Root.nsmap

If the XML file uses the default namespace:

>>>'http://schemas.microsoft.com/developer/msbuild/2003'}

To find a node, use the XPath:

def GetNode (tree, node):     " default " = Tree.getroot ()    = root.nsmap    = Nsmap[none] Nsmap.pop (None)           return Tree.xpath ("//{0}:{1}". Format (ns_prefix, node), namespaces= NSMAP)

To add a child node:

Etree. subelement (node, tag)

Finally, write to the XML file:

" WB " ) Tree.write (filehandler, encoding="utf-8", Xml_declaration=true, Pretty_print =True) filehandler.close ()

XPath Basics

XPath uses a path expression to pick a node or set of nodes in an XML document.

An expression Describe
NodeName From the child node of the current node, select all the nodes tagged as nodename
/ Select from the root node
// Select any location
. Select the current node
.. Select parent Node
@att Select a node with an attribute att
[] Predicate

Example:

1 tree.xpath ("//folder[@Include]")2#  Select the Folder node with the Include attribute 3 tree.xpath ("//itemgroup[./folder]")
4 Tree.xpath ("//itemgroup[folder]")5# Select the ItemGroup node that contains the Folder child node

Traverse Directory:

There are two ways to traverse a directory: Os.list_dir and Os.walk. The respective use cases:

1 ImportOS2 3 defList_dir (rootdir):4      forListsinchOs.listdir (rootdir):5Path =Os.path.join (RootDir, lists)6         Print(PATH)7         ifOs.path.isdir (path):8 list_dir (path)9 Ten defWalk (RootDir): One      forRoot, dirs, filesinchOs.walk (rootdir): A          forDinchdirs: -             Print(Os.path.join (root, D)) -          forFinchFiles: the             Print(Os.path.join (root, f))

[Python applet] Use lxml to modify the XML file and traverse the directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.