[使用lxml添加名称空间与根元素不同的xml子元素

问题描述 投票:0回答:1

这是我要构建的xml的简化版本:

<BizData xmlns="urn:iso:std:iso:20022:tech:xsd:head.003.001.01" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:n1="urn:iso:std:iso:20022:tech:xsd:head.001.001.02" 
  xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd">
  <Hdr>
   <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"             
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
    xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd"> 
   </AppHdr>
  </Hdr>
 </BizData>

Python代码

from lxml import etree as etree

if __name__ == '__main__':
attr_qname = etree.QName('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')
nsmap = {None: 'urn:iso:std:iso:20022:tech:xsd:head.003.001.01',
         'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
         'n1': 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02'
        }
root = etree.Element('BizData',
                     {attr_qname: 'urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd'},
                     nsmap)

hdr = etree.Element('hdr')
attr_qname = etree.QName('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')
nsmap = {None: 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02',
         'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
         }

app_hdr = etree.Element('AppHdr',
                {attr_qname: 'urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd'},
                nsmap)
hdr.append(app_hdr)
root.append(hdr)

在附加到根目录之前打印hdr时,我得到正确的输出:

<Hdr>
 <AppHdr xmlns="urn:iso:std:iso:20022:tech:xsd:head.001.001.02"             
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         
  xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd"> 
 </AppHdr>
</Hdr> 

但是在附加到根之后,命名空间xmlnsxmlns:xsi消失了:

<BizData xmlns:n1="urn:iso:std:iso:20022:tech:xsd:head.001.001.02" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
 xmlns="urn:iso:std:iso:20022:tech:xsd:head.003.001.01" 
 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.003.001.01 head.003.001.02_DTCC.xsd">
 <hdr>
  <AppHdr xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:head.001.001.02 head.001.001.02.xsd"/>
 </hdr>
</BizData>

我尝试使用set函数设置xmlns:xsi,但这会导致错误..not a valid attribute...

有人有想法吗?

python xml namespaces lxml
1个回答
0
投票

DIRTY WORKAROUND

© www.soinside.com 2019 - 2024. All rights reserved.