使用元素树删除xml中的一些元素并附加其他xml文件中的元素

时间:2017-06-20 16:17:40

标签: xml python-2.7 elementtree file-handling

XML file1:

<?xml version="1.0"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/2008/CIM-schema-cim13#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:ConnectivityNode rdf:ID="S1_CN1">
<cim:IdentifiedObject.name>Connectivity Node 1</cim:IdentifiedObject.name>
<cim:ConductingEquipment.Terminals rdf:resource="#S1_T1" />
</cim:ConnectivityNode>

<cim:BusbarSection rdf:ID="S2_BB2">
<cim:IdentifiedObect.name>Busbar Section S2_BB2</cim:IdentifiedObect.name>
<cim:Equipment.MemberOf_EquipmentContaiber rdf:resource="#S2" />
</cim:BusbarSection>
</rdf:RDF>

XML file2:

<?xml version="1.0"?>
<rdf:RDF xmlns:cim="http://iec.ch/TC57/2008/CIM-schema-cim13#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<cim:Substation rdf:ID="S1">
<cim:IdentifiedObject.name>1000kV/13800kV</cim:IdentifiedObject.name>
</cim:Substation>
</rdf:RDF>

我的主要目的是通过搜索父节点(like cim:ConnectivityNode)的属性来实际删除特定父节点下的完整树,将rdf:Rdf的子节点从xml file 2添加到{{1}作为其根xml1的孩子之一。这可能吗?

编辑1:我尝试过的代码

rdf:Rdf

输出:

from elementtree import ElementTree as etree
from IECcimextract import*
tree= etree.parse(r'N:/myinternwork/files xml of bus systems/temp.xml')
root= tree.getroot()
cim= "{http://iec.ch/TC57/2008/CIM-schema-cim13#}" #namespace uri for cim
rdf= "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}" #namespace uri for rdf
tree2bus2break=etree.parse(r'N:/myinternwork/files xml of bus systems/9busi_in_61850.xml')
rootdbdb=tree2bus2break.getroot()
def convfun():
    for child in root:
        if (child.attrib['{http://www.w3.org/1999/02/22-rdf-syntax-ns#}ID'])[0]+(child.attrib['{http://www.w3.org/1999/02/22-rdf-syntax-ns#}ID'])[1]==S1:
            root.remove(child)

 convfun()
 tree.write("N:/myinternwork/files xml of bus systems/temp.xml")

为什么命名空间cim不在输出中?

实际上我减少了代码以精确定位它,有许多父子树,其属性值以S1开头,我使用相同的代码,它只删除了一些以S1属性值开头的子树但不是全部他们为什么会这样?

提前致谢

更新1,关于mzjn发表的评论的查询

<?xml version="1.0"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<ns1:BusbarSection rdf:ID="S2_BB2" xmlns:ns1="http://iec.ch/TC57/2008/CIM-schema-cim13#">>
<ns1:IdentifiedObect.name>Busbar Section S2_BB2</cim:IdentifiedObect.name>
<ns1:Equipment.MemberOf_EquipmentContaiber rdf:resource="#S2" />
</ns1:BusbarSection>
</rdf:RDF>

现在运行这个python代码

<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
</country>
</data>   

它没有显示,但是好像我导入为

import xml.etree.ElementTree as etree
tree= etree.parse(r'N:/myinternwork/files xml of bus systems/note.xml')
root= tree.getroot()
print root

它不会抛出任何错误!是什么原因?

0 个答案:

没有答案