<!-- /* Font Definitions */ @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:宋体; mso-font-kerning:1.0pt;} a:link, span.MsoHyperlink {color:blue; text-decoration:underline; text-underline:single;} a:visited, span.MsoHyperlinkFollowed {color:purple; text-decoration:underline; text-underline:single;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} -->
问题来源:
昨天用python写了一个VC工程配置设置的脚本,查找xml元素,都是用操作dom的方法,一级一级的向下找,用很多像getElementsByName函数的操作,很烦锁.到写完了脚本之后,突然想到是不是能有一种方法通过一个表达式直接找到一个xml元素呢,很幸运,曾经见过XPath,似乎它就是我要找的东西,嘿嘿!简略的作一下调查,以备不时之需。
重新描述一下我的问题:
通过一个表达式精确定位某个XML元素,查找方式包括:通过名字,属性,内容做为关键字.再引申一下,可以方便创建一个xml结点.
一个示例,展示XPath的基本用法、功能:
1. bookstore/book 选取所有属于 bookstore 的子元素的 book 元素。
2. //title[@lang='eng'] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
3. /bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
通过三个例子,可以发现,通过XML结点的名字组成一个路径,可以精确定位一个结点或一组结点,此外,如果你想找拥有某个属性的结点,可以作到吗?呵呵,例子2就是答案。例子3说明还可以通过位置来定位xml结点。这三个例子只是抛砖引玉,更多xpath语法,详见:
http://www.w3school.com.cn/xpath/xpath_syntax.asp
貌似不能够利用XPath创建结点,XPath是专门为查询检索使用的工具,因为XPath可以定位一组结点,所以如果要利用XPath来创建结点的话,必需使用XPath约束的子集。如果谁知道有类似东西,请不吝赐教,非常感谢。
XPath教程
http://www.w3school.com.cn/xpath/index.asp
关于XPath结点的概念对于操作XML来说是必须要了解的。
http://www.w3school.com.cn/xpath/xpath_nodes.asp
python中支持XPath的库:
xml.etree.ElementTree 标准python安装包中自带
4suite 需手动安装 参考:http://4suite.org/index.xhtml
附例程:
下面的示例,展示了xml.etree.ElementTree 如何操作xpath可以更方便的找到元素。其中方式一为标准dom方式,而方式二为使用xpath。
import xml.etree.ElementTree
def detail_anchor(element):
if element.tag == "a":
attributes = element.attrib
if "href" in attributes.keys():
print "'%s' is at URL '%s'." % (element.text,attributes['href'])
if "name" in attributes.keys():
print "'%s' anchors '%s'." % (element.text,attributes['name'])
################方式一###########################################
def report(element):
detail_anchor(element)
for x in element.getchildren():
report(x)
report(xml.etree.ElementTree.parse("913.xml").getroot())
################方式二###########################################
for element in elementtree.ElementTree.parse("913.xml").findall("//a"):
detail_anchor(element)