Python ElementTree 解析指定命名空间的xml,pythonelementtree,如果xml指定了命名空间


如果xml指定了命名空间,直接通过find(tag)的方式就得不到节点了,必须添加节点的命名空间,如下POM文件中的xml文档片段:

<?xml version="1.0" encoding="UTF-8"?><project xsi:schemaLocation=" http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://maven.apache.org/POM/4.0.0">    <modelVersion>4.0.0</modelVersion>    <groupId>org.springmodules</groupId>...

如果要通过下面代码获得groupId节点:

dom.find('//groupId')

会返回None,就是说没找到节点,原因是xml文档指定了命名空间,而我们在find方法的参数中没指定命名空间。

def get_namespace(element):  m = re.match('\{.*\}', element.tag)  return m.group(0) if m else ''namespace = get_namespace(tree.getroot())print tree.find('//{0}groupId'.format(namespace)).text

评论关闭