我想使用"findall"方法在ElementTree模块中找到源xml文件的一些元素.
但是,源xml文件(test.xml)具有命名空间.我将部分xml文件截断为样本:
<?xml version="1.0" encoding="iso-8859-1"?>
<XML_HEADER xmlns="http://www.test.com">
<TYPE>Updates</TYPE>
<DATE>9/26/2012 10:30:34 AM</DATE>
<COPYRIGHT_NOTICE>All Rights Reserved.</COPYRIGHT_NOTICE>
<LICENSE>newlicense.htm</LICENSE>
<DEAL_LEVEL>
<PAID_OFF>N</PAID_OFF>
</DEAL_LEVEL>
</XML_HEADER>
Run Code Online (Sandbox Code Playgroud)
示例python代码如下:
from xml.etree import ElementTree as ET
tree = ET.parse(r"test.xml")
el1 = tree.findall("DEAL_LEVEL/PAID_OFF") # Return None
el2 = tree.findall("{http://www.test.com}DEAL_LEVEL/{http://www.test.com}PAID_OFF") # Return <Element '{http://www.test.com}DEAL_LEVEL/PAID_OFF' at 0xb78b90>
Run Code Online (Sandbox Code Playgroud)
虽然它可以工作,因为有一个名称空间"{http://www.test.com}",在每个标记前面添加一个名称空间是非常不方便的.
使用"find","findall"等方法时,如何忽略命名空间?
我正在处理一些XML数据,这些数据在每个文件的某些位置重新定义了命名空间.我试图从文档中提取特定类型的所有标记,而不管标记位于XML中的活动名称空间是什么.
我正在findall('.//{namespace}Tag')寻找我正在寻找的元素.但是永远不知道{namespace}文件中任何给定点的内容是什么,会让它命中或遗漏我是否会返回所有请求的标签.
有没有办法返回所有Tag元素,无论{namespace}它们属于什么?有什么东西沿着findall('.//{wildcard}Tag')?
我正在使用 google 的一些数据 API,使用 python 中的 lxml 库。命名空间在这里是一个很大的麻烦。对于我正在做的很多工作(主要是 xpath 的东西),最好直接忽略它们。
有没有一种简单的方法可以忽略 python/lxml 中的 xml 命名空间?
谢谢!
我正在尝试使用 Python 和 lxml 解析 vcxproj。当我尝试这样做时,除非我删除<Project >.
这是我的 .vcxproj(我将其缩减为测试):
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDebug|Win32">
<Configuration>ReleaseDebug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="ReleaseDebug|x64">
<Configuration>ReleaseDebug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)
我的python代码:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from lxml import etree
tree = etree.parse("core.xml")
for conf in tree.xpath("/Project/ItemGroup/ProjectConfiguration/Configuration"):
print(conf.text)
Run Code Online (Sandbox Code Playgroud)
如果我这样运行,脚本可以工作但什么也不显示。如果我DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"在节点项目脚本中删除工作...
我是 xml …
python ×3
elementtree ×2
xml ×2
api ×1
find ×1
findall ×1
lxml ×1
namespaces ×1
python-3.x ×1
vcxproj ×1
xml-parsing ×1