首页 > 解决方案 > 如何在python中复制命名空间

问题描述

我的输入文件是:aa.xml

<?xml version="1.0" encoding="utf-8"?>
<CSDOC xmlns:cs="http://www.google-try.com/cs"
    xmlns:ci="http://www.google-try.com/ci">
    <cs:body>
        <cs:content>
            <cs:appendix>
                <blockquote>
                    <p>
                        <text>
                            This is a text to try this programm is correct or not. <ci:cite>My name is john</ci:cite> this is a test.
                        </text>
                    </p>
                </blockquote>
            </cs:appendix>
        </cs:content>
    </cs:body>
</CSDOC>

我的python代码是:

from lxml import etree
import xml.etree.ElementTree as ET
import copy
XMLDoc = etree.parse(open('aa.xml'))
v = '/CSDOC/cs:body/cs:content/cs:appendix/blockquote/p/text/ci:cite'
for Node in XMLDoc.xpath(v,namespaces={
       'cs': 'http://www.google-try.com/cs',
       'ci': 'http://www.google-try.com/ci',
       }):
    m2 = copy.deepcopy(Node)
    print(ET.tostring(m2))

输出是:

b'<ns0:cite xmlns:ns0="http://www.google-try.com/ci">My name is john</ns0:cite> this is a test.\n\t\t\t\t\t\t'ut

期望的输出是:

<ci:cite>My name is john</ci:cite>

实际上,我只想复制选择或 xpath 元素内容,但我的代码是复制带有父元素内容且没有命名空间的选择内容。请建议如何仅使用命名空间复制 xpath 元素内容。

标签: pythonpython-3.xelementtree

解决方案


推荐阅读