使用 Python 操作 xml

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

我使用的是Python 3.9。我有一个像这样的嵌套 xml 文档字符串

payload_xml = """
<AllData>
   <MyPayload>
     ...
       ...
     ...
   </MyPayload>
</AllData>
"""

现在我想创建另一个父 xml 文档字符串,并将此有效负载提取到新创建的 xml 文档中,如下所示

新 XML

<Full_Message prop1="" prop2="">
   <Header>
     <headerValue1>     </headerValue1>
     <headerValue2>     </headerValue2>
     <headerValue3>     </headerValue3>
     <NestedValues>
        <someval1> </someval>
     </NestedValues>
   </Header>
   <Body>
     <!--Insert MyPayload xml string here ignoring AllData node-->
   </Body>
</Full_Message>

这是我目前所在的位置

  from lxml import etree

  FullMessage_root = etree.Element("Full_Message")
  AllData_root = etree.fromstring(payload_xml)

  payload_only = AllData_root[0]
  FullMessage_root.append(payload_only)
  FullMessage_root.insert(0, etree.Element("Header"))
  FullMessage_root.insert(1, etree.Element("Body"))
  FullMessage_root.attrib['prop1']='hello world'

这会导致:

<Full_Message prop1="hello world">
  <Header/>
  <Body/>
  <MyPayload>
  </MyPayload>
</Full_Message>

如何将

<MyPayload>
嵌套在
<Body>
标签中并在
<Header>
中创建多个嵌套值?

python python-3.x lxml
1个回答
0
投票

以下是实现您目标的一种方法。我们从上到下逐层创建新的 XML,并使用

append
将子元素附加到父元素。

import xml.etree.ElementTree as ET


def create_elements(parent_ele, child_tags, child_vals):
    for tag, val in zip(child_tags, child_vals):
        ele = ET.Element(tag)
        if val:
            ele.text = val
        parent_ele.append(ele)


payload_xml = '''
<AllData>
    <MyPayload>
        Foo
    </MyPayload>
</AllData>
'''


# Create root
root = ET.Element('Full_Message')
root.set('prop1', 'some prop')
root.set('prop2', 'other prop')

# Add elements to root
create_elements(
    root,
    ['Header', 'Body'],
    [None] * 2,  # no text value attached to header and body
)

# Add elements to header
create_elements(
    root.find('Header'),
    ['headerValue1', 'headerValue2', 'headerValue3', 'NestedValues'],
    ['val1', 'val2', 'val3', None],  # note that no text value attached to NestedValues
)
# Add elements to NestedValues
create_elements(
    root.find('Header').find('NestedValues'),
    ['someval1', 'someval2', 'someval3'],
    ['nested val1', 'nested val2', 'nested val3'],
)

# Insert payload
AllData_root = ET.ElementTree(ET.fromstring(payload_xml)).getroot()
root.find('Body').append(AllData_root)

# print the new XML
ET.indent(root)
print(ET.tostring(root, encoding='unicode'))

输出将是

<Full_Message prop1="some prop" prop2="other prop">
  <Header>
    <headerValue1>val1</headerValue1>
    <headerValue2>val2</headerValue2>
    <headerValue3>val3</headerValue3>
    <NestedValues>
      <someval1>nested val1</someval1>
      <someval2>nested val2</someval2>
      <someval3>nested val3</someval3>
    </NestedValues>
  </Header>
  <Body>
    <AllData>
      <MyPayload>
        Foo
    </MyPayload>
    </AllData>
  </Body>
</Full_Message>
© www.soinside.com 2019 - 2024. All rights reserved.