【问题标题】:copying an XML node, modifying it & copying it复制 XML 节点,修改它并复制它
【发布时间】:2022-01-16 11:34:18
【问题描述】:

您有以下代码,我尝试多次复制某个 XML 节点 并在每次根据列表插入一个小的修改。

问题陈述是:我总是收到 list4xml 上的最后一项,复制了所有其他复制的节点,我想在每个索引上更改

temp= copy.deepcopy(root[1][0])  # i copy the node 
ind=0

for i in list4xml:
    temp[0][0][1].attrib['ExternalSource']=i
    root[1].insert(ind, temp)
    ind+=1
    if (ind>len(list4xml)):
        break
    

似乎以某种方式修改 temp 会影响根目录。 如何断开这两个项目。

我的输入 xml 看起来像这样。

<?xml version="1.0" encoding="utf-8"?>
<Site SiteName="abcdefg" SiteType="128">
  <FileDescription VersionOfObject="3.0" SourceAppName="abcd" DataType="IPSequenceData" />
  <DataSetCollection>
    <DataSet Attempt="0" Quadrant="0" Frame="0">
      <ReportData>
        <ImageData>
          <DataFile FileTypeID="312" FileTypeName="Golden Image" ExternalSource="5.bmp" />
          <DataFile FileTypeID="313" FileTypeName="Scanned Image" ExternalSource="1.3_1.bmp" />
        </ImageData>
        <ParamValues>
          <ParamValue ParTypeID="8" ParID="7" ParName="Location Uncertainty" Value="20" />
        </ParamValues>
      </ReportData>
      <ResultInfo Result="True" BestMark="0.7781224" SecondMark="0">
        <SearchRegion X="0" Y="0" Width="640" Height="480" />
        <RequiredPoint X="320" Y="240" />
        <RoiCenter X="320" Y="240" />
        <ModelCenterOnTarget X="320" Y="230" />
      </ResultInfo>
      <GmpData ExternalSource="abcd_efg.xml" />
    </DataSet>
  </DataSetCollection>
</Site>

我试图用他的孩子多次复制整个 DataSet 节点 并且对于每个编辑属性 ***ExternalSource="1.3_1.bmp" ***

我得到的结果是所有复制的节点都包含最后一项 list4xml 列表,而不是每个节点的不同值

【问题讨论】:

  • 请编辑您的问题,并添加以下内容:(1) 输入 XML,(2) 所需输出,(3) 应用逻辑。

标签: python xml


【解决方案1】:

我设法通过以下代码解决了 将 copy.deepcopy 放入循环中 & 仅在我修改节点后插入新节点

ind=0
for i in list4xml:
    # root[1].append(temp)
    # root[1].copy.deepcopy(temp)
    temp = copy.deepcopy(root[1][0])
    temp[0][0][0].attrib['ExternalSource'] = list4xml[0]
    temp[0][0][1].attrib['ExternalSource']=i
    root[1].insert(ind, temp)
    ind+=1
    if (ind>len(list4xml)):
        break

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多