XPath如何处理XML命名空间?
如果我使用
/IntuitResponse/QueryResponse/Bill/Id
Run Code Online (Sandbox Code Playgroud)
要解析下面的XML文档,我得到0个节点.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3"
time="2016-10-14T10:48:39.109-07:00">
<QueryResponse startPosition="1" maxResults="79" totalCount="79">
<Bill domain="QBO" sparse="false">
<Id>=1</Id>
</Bill>
</QueryResponse>
</IntuitResponse>
Run Code Online (Sandbox Code Playgroud)
但是,我没有在XPath中指定命名空间(即http://schema.intuit.com/finance/v3
不是路径的每个标记的前缀).Id
如果我没有明确告诉它,XPath怎么知道我想要哪个?我想在这种情况下(因为只有一个命名空间)XPath可以xmlns
完全忽略它.但如果有多个名称空间,事情可能会变得丑陋.
有没有办法在python ElementTree中定义默认/未固定的命名空间?这似乎不起作用......
ns = {"":"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("version", ns))
Run Code Online (Sandbox Code Playgroud)
这也不是:
ns = {None:"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("version", ns))
Run Code Online (Sandbox Code Playgroud)
这样做,但后来我必须为每个元素添加前缀:
ns = {"mvn":"http://maven.apache.org/POM/4.0.0"}
pom = xml.etree.ElementTree.parse("pom.xml")
print(pom.findall("mvn:version", ns))
Run Code Online (Sandbox Code Playgroud)
在OSX上使用Python 3.5.
编辑:如果答案是"不",你仍然可以获得赏金:-).我只想要一个花费大量时间使用它的人明确的"不".
我是xml解析和Python的新手,所以请耐心等待.我正在使用lxml来解析wiki转储,但我只想要每个页面,它的标题和文本.
现在我有了这个:
from xml.etree import ElementTree as etree
def parser(file_name):
document = etree.parse(file_name)
titles = document.findall('.//title')
print titles
Run Code Online (Sandbox Code Playgroud)
目前,冠军没有返回任何东西.我已经看过像这样的前面的答案:ElementTree findall()返回空列表和lxml文档,但大多数事情似乎都是为解析HTML而定制的.
这是我的XML的一部分:
<mediawiki xmlns="http://www.mediawiki.org/xml/export-0.7/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.7/ http://www.mediawiki.org/xml/export-0.7.xsd" version="0.7" xml:lang="en">
<siteinfo>
<sitename>Wikipedia</sitename>
<base>http://en.wikipedia.org/wiki/Main_Page</base>
<generator>MediaWiki 1.20wmf9</generator>
<case>first-letter</case>
<namespaces>
<namespace key="-2" case="first-letter">Media</namespace>
<namespace key="-1" case="first-letter">Special</namespace>
<namespace key="0" case="first-letter" />
<namespace key="1" case="first-letter">Talk</namespace>
<namespace key="2" case="first-letter">User</namespace>
<namespace key="3" case="first-letter">User talk</namespace>
<namespace key="4" case="first-letter">Wikipedia</namespace>
<namespace key="5" case="first-letter">Wikipedia talk</namespace>
<namespace key="6" case="first-letter">File</namespace>
<namespace key="7" case="first-letter">File talk</namespace>
<namespace key="8" case="first-letter">MediaWiki</namespace>
<namespace key="9" case="first-letter">MediaWiki talk</namespace>
<namespace key="10" …
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个计算pptx
文档中字数的函数。问题是我不知道如何只找到这种标签:
<a:t>Some Text</a:t>
当我尝试:print xmlTree.findall('.//a:t')
,它返回
SyntaxError: 在前缀映射中找不到前缀“a”
你知道怎么做才能让它发挥作用吗?
这是函数:
def get_pptx_word_count(filename):
import xml.etree.ElementTree as ET
import zipfile
z = zipfile.ZipFile(filename)
i=0
wordcount = 0
while True:
i+=1
slidename = 'slide{}.xml'.format(i)
try:
slide = z.read("ppt/slides/{}".format(slidename))
except KeyError:
break
xmlTree = ET.fromstring(slide)
for elem in xmlTree.iter():
if elem.tag=='a:t':
#text = elem.getText
#num = len(text.split(' '))
#wordcount+=num
Run Code Online (Sandbox Code Playgroud) 我使用 python 2.7 和 ElementTree 库。
我无法使用 lxml lib。
我需要获取字符串中的名称空间namespace_string
。为了填充我的命名空间字典。
我的XML:
<?xml version="1.0" encoding="UTF-8"?>
<AX_Bestandsdatenauszug
xmlns="http://www.adv-online.de/namespaces/adv/gid/6.0"
xmlns:adv="http://www.adv-online.de/namespaces/adv/gid/6.0"
xmlns:gco="http://www.isotc211.org/2005/gco"
xmlns:gmd="http://www.isotc211.org/2005/gmd"
xmlns:gml="http://www.opengis.net/gml/3.2"
xmlns:ows="http://www.opengis.net/ows"
xmlns:wfs="http://www.adv-online.de/namespaces/adv/gid/wfs"
xmlns:wfsext="http://www.adv-online.de/namespaces/adv/gid/wfsext"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ogc="http://www.adv-online.de/namespaces/adv/gid/ogc"
xsi:schemaLocation="http://www.adv-online.de/namespaces/adv/gid/6.0 NAS-Operationen.xsd">
<enthaelt>
<gml:featureMember>
<xmlstuff>....a lot of xml stuff....</xmlstuff>
</gml:featureMember>
</enthaelt>
</AX_Bestandsdatenauszug>
Run Code Online (Sandbox Code Playgroud)
代码:
import clr
import sys
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
sys.path.append("C:\Program Files (x86)\IronPython 2.7\Lib")
import xml.etree.ElementTree as ET
from io import StringIO
xml="file.xml"
tree = ET.parse(xml)
root = tree.getroot()
my_schema = "namespace_string"
my_namespaces = dict([node for _, node in …
Run Code Online (Sandbox Code Playgroud) 如何告诉ElementTree忽略XML文件中的命名空间?
例如,我更愿意查询modelVersion
(如语句1中)而不是 {http://maven.apache.org/POM/4.0.0}modelVersion
(如语句2中所示).
pom="""
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
</project>
"""
from xml.etree import ElementTree
ElementTree.register_namespace("","http://maven.apache.org/POM/4.0.0")
root = ElementTree.fromstring(pom)
print 1,root.findall('modelVersion')
print 2,root.findall('{http://maven.apache.org/POM/4.0.0}modelVersion')
1 []
2 [<Element '{http://maven.apache.org/POM/4.0.0}modelVersion' at 0x1006bff10>]
Run Code Online (Sandbox Code Playgroud) 我有一个有效的 XHTML 文件。当我做
import xml.etree.ElementTree as ET
print ET._namespace_map
Run Code Online (Sandbox Code Playgroud)
它列出了:
'http://www.w3.org/1999/xhtml': 'html'
Run Code Online (Sandbox Code Playgroud)
当我做:
root.find('{http://www.w3.org/1999/xhtml}head')
Run Code Online (Sandbox Code Playgroud)
它发现:
<Element '{http://www.w3.org/1999/xhtml}head' at 0x104647168>
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时:
root.find('html:head')
Run Code Online (Sandbox Code Playgroud)
它抱怨:
SyntaxError: prefix 'html' not found in prefix map
Run Code Online (Sandbox Code Playgroud)
是否可以find
使用语法找到名称间隔元素ns:element
?
我正在尝试用 Python 解析 XML 文档,以便我可以对数据进行操作并写出一个新文件。我正在使用的完整文件在这里,但这里有一个摘录:
<?xml version="1.0" encoding="UTF-8"?>
<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">
<ERRORCODE>0</ERRORCODE>
<PRODUCT BUILD="09-11-2013" NAME="FileMaker" VERSION="ProAdvanced 12.0v5"/>
<DATABASE DATEFORMAT="M/d/yyyy" LAYOUT="" NAME="All gigs 88-07.fmp12" RECORDS="746" TIMEFORMAT="h:mm:ss a"/>
<METADATA>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Country" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Year" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="City" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="State" TYPE="TEXT"/>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="Theater" TYPE="TEXT"/>
</METADATA>
<RESULTSET FOUND="746">
<ROW MODID="3" RECORDID="32">
<COL>
<DATA/>
</COL>
<COL>
<DATA>1996</DATA>
</COL>
<COL>
<DATA>Pompano Beach</DATA>
</COL>
<COL>
<DATA>FL</DATA>
</COL>
<COL>
<DATA>First Presbyterian Church</DATA>
</COL>
</ROW>
<ROW MODID="3" …
Run Code Online (Sandbox Code Playgroud) 所以我试图解析一些开放数据来构建数据库。\n这就是我所做的:
\n\n# -*- coding: utf-8 -*-\nimport urllib\nimport xml.etree.ElementTree as ET\n\nurl = \'http://opendata.cwb.gov.tw/govdownload?dataid=C-A0008-001&authorizationkey=rdec-key-123-45678-011121314\'\n\nroot = ET.parse(urllib.urlopen(url)).getroot()\n\nlocations = root.findall(\'dataset/location\')\nprint type(locations)\nprint "Counts:", len(locations)\n
Run Code Online (Sandbox Code Playgroud)\n\n它返回:
\n\nCounts: 0\n
Run Code Online (Sandbox Code Playgroud)\n\n我尝试解析其他一些 xml 数据(更改 url),效果很好
\n\n我正在处理的 xml 数据大致如下:
\n\n<?xml version="1.0" encoding="UTF-8"?><cwbopendata xmlns="urn:cwb:gov:tw:cwbcommon:0.1">\n<identifier>0f819d32-297a-4512-9654-990a565bd080</identifier>\n<sender>weather@cwb.gov.tw</sender>\n<sent>2016-05-23T16:07:06+08:00</sent>\n<status>Actual</status>\n<msgType>Issue</msgType>\n<dataid>CWB_A0008</dataid>\n<scope>Public</scope>\n<dataset>\n <location>\n <stationId>72C44</stationId>\n <time>\n <dataTime>105 4_2</dataTime>\n </time>\n <weatherElement>\n <elementName>\xe5\xb9\xb3\xe5\x9d\x87\xe6\xb0\xa3\xe6\xba\xab</elementName>\n <elementValue>\n <value>21.1</value>\n </elementValue>\n .\n .\n .\n </location>\n <location>\n .\n . \n .\n
Run Code Online (Sandbox Code Playgroud)\n\n抱歉,我是 python 和 ElementTree 的新手,希望得到一些好的建议,谢谢
\n我正在尝试从<v:imagedata r:id="rId7" o:title="1-REN"/>
带有命名空间的 Word 文档中查找所有内容xmlns:v="urn:schemas-microsoft-com:vml"
,但我无法弄清楚语法到底是什么。
这些文档只涵盖了非常直接的情况,并且在加入了 URN 和 VML 组合后,我似乎无法让我在网上看到的任何示例都可以工作。有人碰巧知道它是什么吗?
我正在尝试做这样的事情:
namespace = {'v': "urn:schemas-microsoft-com:vml"}
results = ET.fromstring(xml).findall("imagedata", namespace)
for image_id in results:
print(image_id)
Run Code Online (Sandbox Code Playgroud)
编辑:@aneroid 所写的是 1000% 正确的答案并且非常有帮助。你应该点赞。也就是说,在理解了所有这些之后 - 我选择了 BS4 答案,因为它在两行中完成了我需要的全部工作。如果您实际上并不关心命名空间,那似乎更容易。
这是我第一次尝试用 python 解析 XML,所以答案可能很简单,但我无法弄清楚。
我正在使用 ElementTree 来解析一些 XML 文件。问题是,当具有此属性时,我无法在树内获得任何结果:
<package xmlns="http://apple.com/itunes/importer" version="software5.1">
Run Code Online (Sandbox Code Playgroud)
当删除这个属性时,一切都很好。需要明确的是,我的意思是将 XML 文件的第一行更改为:
<package>
Run Code Online (Sandbox Code Playgroud)
一切都很好。
我究竟做错了什么?
这是我的代码:
import xml.etree.ElementTree as ET
tree = ET.parse('metadataCopy.xml')
root = tree.getroot()
p = root.find(".//intervals/interval")
print p
for interval in root.iterfind(".//intervals/interval"):
start_date = interval.find('start_date').text
end_date = interval.find('end_date').text
print start_date, end_date
Run Code Online (Sandbox Code Playgroud)
请帮忙。谢谢!
更新:XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://apple.com/itunes/importer" version="software5.1">
<metadata_token>TOKEN</metadata_token>
<provider>Provider Name</provider>
<team_id>Team_ID_Here</team_id>
<software>
<!--Apple ID: 01234567-->
<vendor_id>vendorSKU</vendor_id>
<read_only_info>
<read_only_value key="apple-id">01234567</read_only_value>
</read_only_info>
<software_metadata>
<versions>
<version string="1.0">
<locales>
<locale name="en-US">
<title>title text</title>
<description>Description text</description> …
Run Code Online (Sandbox Code Playgroud) 我正在将word文档转换为xml,以使用以下代码进行比较:
word = win32com.client.Dispatch('Word.Application')
wd = word.Documents.Open(inFile)
# Converts the word infile to xml outfile
wd.SaveAs(outFile,11)
wd.Close()
dom=parse(outFile)
Run Code Online (Sandbox Code Playgroud)
我得到的xml文件看起来像:
<?xml version="1.0" encoding="utf-8"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument w:embeddedObjPresent="no" w:macrosPresent="no" w:ocxPresent="no" xml:space="preserve" xmlns:aml="http://schemas.microsoft.com/aml/2001/core" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:sl="http://schemas.microsoft.com/schemaLibrary/2003/core" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:wsp="http://schemas.microsoft.com/office/word/2003/wordml/sp2" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint">
<w:ignoreSubtree w:val="http://schemas.microsoft.com/office/word/2003/wordml/sp2"/>
<w:shapeDefaults>
<o:shapedefaults spidmax="1027" v:ext="edit"/>
<o:shapelayout v:ext="edit">
<o:idmap data="1" v:ext="edit"/>
</o:shapelayout>
</w:shapeDefaults>
<w:body>
<wx:sect>
<w:tbl>
<w:tblGrid>
<w:gridCol w:w="200"/>
...
</w:tblGrid>
<w:pict>
<v:shapetype coordsize="21600,21600" filled="f" id="_x0000_t75" o:preferrelative="t" o:spt="75" path="m@4@5l@4@11@9@11@9@5xe" stroked="f">
<v:stroke joinstyle="miter"/>
<v:formulas>
<v:f eqn="if lineDrawn pixelLineWidth 0"/>
... …
Run Code Online (Sandbox Code Playgroud) 我有一个xml字符串,我需要在python中解析,如下所示:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<PostLoadsResponse xmlns="http://webservices.truckstop.com/v11">
<PostLoadsResult xmlns:a="http://schemas.datacontract.org/2004/07/WebServices.Objects" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Errors xmlns="http://schemas.datacontract.org/2004/07/WebServices">
<Error>
<ErrorMessage>Invalid Location</ErrorMessage>
</Error>
</Errors>
</PostLoadsResult>
</PostLoadsResponse>
</s:Body>
</s:Envelope>'
Run Code Online (Sandbox Code Playgroud)
我无法使用xmltree来获取此树的错误消息,如下所示:
import xml.etree.ElementTree as ET
ET.fromstring(text).findall('{http://schemas.xmlsoap.org/soap/envelope/}Body')[0].getchildren()[0].getchildren()[0].getchildren()
Run Code Online (Sandbox Code Playgroud) xml ×12
python ×11
elementtree ×8
python-2.7 ×3
parsing ×2
xml-parsing ×2
xpath ×2
dictionary ×1
findall ×1
lxml ×1
namespaces ×1
python-3.x ×1
urn ×1
vml ×1