学习笔记:Python XML解析

Python XML解析

参考资料:

菜鸟教程:https://www.runoob.com/python/python-xml.html
官网文档:https://docs.python.org/3.6/library/markup.html

Python由xml包(Lib/xml)提供对XML的支持。

Python处理XML主要有两种模型,xml.domxml.sax分别定义了两种处理模型的接口:

  • 事件驱动模型:SAX (Simple API for XML),在解析XML的过程中触发一个个的事件,并调用用户定义的回调函数,以此来处理XML文件。
  • 文档对象模型:DOM (Document Object Model),将 XML 数据在内存中解析成一个树,通过对树的操作来操作XML。

The XML handling submodules are:

xml.etree.ElementTree

xml.dom

手册:https://docs.python.org/3.6/library/xml.dom.html

InterfaceSectionPurpose
DOMImplementationDOMImplementation ObjectsInterface to the underlying implementation.
NodeNode ObjectsBase interface for most objects in a document.
NodeListNodeList ObjectsInterface for a sequence of nodes.
DocumentTypeDocumentType ObjectsInformation about the declarations needed to process a document.
DocumentDocument ObjectsObject which represents an entire document.
ElementElement ObjectsElement nodes in the document hierarchy.
AttrAttr ObjectsAttribute value nodes on element nodes.
CommentComment ObjectsRepresentation of comments in the source document.
TextText and CDATASection ObjectsNodes containing textual content from the document.
ProcessingInstructionProcessingInstruction ObjectsProcessing instruction representation.

xml.dom.minidom

import xml.dom.minidom

cproject = r'.cproject'
dom = xml.dom.minidom.parse(cproject)
options = dom.getElementsByTagName('option')
for opt in options:
    if opt.getAttribute('superClass')=='gnu.c.compiler.option.preprocessor.def.symbols':
        nod_text = opt.childNodes[0]
        nod_elem = opt.childNodes[1]
        last_child = opt.lastChild

        nod_text = nod_text.cloneNode(False)
        nod_elem = nod_elem.cloneNode(False)
        nod_elem.setAttribute('value', 'GI_COMMIT="%s"' % git_commit)
        opt.insertBefore(nod_text, last_child)
        opt.insertBefore(nod_elem, last_child)

        nod_text = nod_text.cloneNode(False)
        nod_elem = nod_elem.cloneNode(False)
        nod_elem.setAttribute('value', 'GIT_BRANCH="%s"' % git_branch)
        opt.insertBefore(nod_text, last_child)
        opt.insertBefore(nod_elem, last_child)
        break

f = open(cproject, 'w')
dom.writexml(f, cproject+'.new')

代码功能是修改eclipse的工程文件(.cproject),增加宏定义GIT_COMMIT和GIT_BRANCH,将当前编译版本的源码git commit id和分支名编入版本。

xml.sax

原文链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值