将标签的内容存储在python3中的ElementTree的字符串中

发布于 2025-02-13 12:12:48 字数 1023 浏览 2 评论 0原文

我正在使用Python 3.7.2和ElementTree来复制XML文件中标签的内容。

这是我的XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.003.03">
   <CstmrCdtTrfInitn>
      <GrpHdr>
         <MsgId>nBblsUR-uH..6jmGgZNHLQAAAXgXN1Lu</MsgId>
         <CreDtTm>2016-11-10T12:00:00.000+01:00</CreDtTm> 
         <NbOfTxs>1</NbOfTxs>
         <CtrlSum>6</CtrlSum>
         <InitgPty>
            <Nm>TC 03000 Kunde 55 Protokollr ckf hrung</Nm>
         </InitgPty>
      </GrpHdr>
   </CstmrCdtTrfInitn>
</Document>

我想复制“ MSGID”标签的内容并将其保存为字符串。 我以前已经设法使用微型词来完成此操作,但是由于新的情况,我现在必须与ElementTree解决。 这是带有微型的代码:

dom = xml.dom.minidom.parse('H:\\app_python/in_spsh/{}'.format(filename_string)) 
message = dom.getElementsByTagName('MsgId')
for MsgId in message:
   print(MsgId.firstChild.nodeValue)

现在我想对ElementTree做完全相同的事情。我该如何实现?

I'm using Python 3.7.2 and elementtree to copy the content of a tag in an XML file.

This is my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.003.03">
   <CstmrCdtTrfInitn>
      <GrpHdr>
         <MsgId>nBblsUR-uH..6jmGgZNHLQAAAXgXN1Lu</MsgId>
         <CreDtTm>2016-11-10T12:00:00.000+01:00</CreDtTm> 
         <NbOfTxs>1</NbOfTxs>
         <CtrlSum>6</CtrlSum>
         <InitgPty>
            <Nm>TC 03000 Kunde 55 Protokollr ckf hrung</Nm>
         </InitgPty>
      </GrpHdr>
   </CstmrCdtTrfInitn>
</Document>

I want to copy the content of the 'MsgId' tag and save it as a string.
I've manage to do this with minidom before, but due to new circumstances, I have to settle with elementtree for now.
This is that code with minidom:

dom = xml.dom.minidom.parse('H:\\app_python/in_spsh/{}'.format(filename_string)) 
message = dom.getElementsByTagName('MsgId')
for MsgId in message:
   print(MsgId.firstChild.nodeValue)

Now I want to do the exact same thing with elementtree. How can I achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坠似风落 2025-02-20 12:12:48

要获取单个元素的文本值,您可以使用 findtext() 方法。需要考虑名称空间。

from xml.etree import ElementTree as ET

tree = ET.parse("test.xml")   # Your XML document
msgid = tree.findtext('.//{urn:iso:std:iso:20022:tech:xsd:pain.001.003.03}MsgId')

使用

msgid = tree.findtext('.//{*}MsgId')

To get the text value of a single element, you can use the findtext() method. The namespace needs to be taken into account.

from xml.etree import ElementTree as ET

tree = ET.parse("test.xml")   # Your XML document
msgid = tree.findtext('.//{urn:iso:std:iso:20022:tech:xsd:pain.001.003.03}MsgId')

With Python 3.8 and later, it is possible to use a wildcard for the namespace:

msgid = tree.findtext('.//{*}MsgId')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文