我正在将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)
我得到的xml文件看起来像:
...
...
...
当我尝试例子时,我不能使用xpath函数(lxml库):
import lxml.etree as et tree = et.parse(xmlFile) for elt in tree.xpath("//w:gridCol"): elt.getparent().remove(elt)
我收到以下错误:
for elt in tree.xpath("//w:gridCol"): File "lxml.etree.pyx", line 2029, in lxml.etree._ElementTree.xpath (src/lxml/lxml.etree.c:45934) File "xpath.pxi", line 379, in lxml.etree.XPathDocumentEvaluator.__call__ (src/lxml/lxml.etree.c:114389) File "xpath.pxi", line 242, in lxml.etree._XPathEvaluatorBase._handle_result (src/lxml/lxml.etree.c:113063) File "xpath.pxi", line 227, in lxml.etree._XPathEvaluatorBase._raise_eval_error (src/lxml/lxml.etree.c:112894) XPathEvalError: Undefined namespace prefix
我做了一些研究,我猜这是一个名称空间问题,但我不知道如何修复它?
在这段代码中:
for elt in tree.xpath("//w:gridCol"):
w:
不是命名空间; 它是一个名称空间前缀,它实际上是实际名称空间的缩写
http://schemas.microsoft.com/office/word/2003/wordml
.如果要使用该xpath
方法在此命名空间中搜索元素,则需要为其提供命名空间前缀到命名空间的映射:
tree.xpath("//w:gridCol", namespaces={ 'w': 'http://schemas.microsoft.com/office/word/2003/wordml', })
另请注意,不要求使用相同的名称空间前缀.以下内容将找到相同的元素:
tree.xpath("//bob:gridCol", namespaces={ 'bob': 'http://schemas.microsoft.com/office/word/2003/wordml' })