在 Python 中将元素值写入 XML

发布于 2024-09-15 05:26:37 字数 277 浏览 1 评论 0原文

我有一个包含键=值对的文本文件。我有另一个 XML 文件,其中包含作为“源”节点的“键”和作为“目标节点”的“值”。

<message>
   <Source>key</Source>
   <Destination>value</Destination>
</message>

假设我得到一个包含相同键但不同值的新文本文件,如何使用 minidom 更改 XML 文件?

这可能吗?

I have a text file containing a key=value pairs. I have another XML file which contains the "key" as "Source" Node and "value" as "Destination Node".

<message>
   <Source>key</Source>
   <Destination>value</Destination>
</message>

Suppose, I get a new text file containing the same keys but different values, how do I go about changing the XML file using the minidom ?

Can this be possible?

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

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

发布评论

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

评论(1

梦里泪两行 2024-09-22 05:26:37

重新生成 XML 文件比就地修改它更容易:

from xml.dom.minidom import Document

doc = Document( )
root = doc.createElement( "root" )

for key, value in <some iterator>:
    message = doc.createElement( "message" )

    source = doc.createElement( "Source" )
    source.appendChild( doc.createTextNode( key ) )

    dest = doc.createElement( "Destination" )
    dest.appendChild( doc.createTextNode( value ) )

    message.appendChild( source )
    message.appendChild( dest )
    root.appendChild( message )

doc.appendChild( root )

print( doc.toprettyxml( ) )

这将打印:

<root>
    <message>
        <Source>
            key
        </Source>
        <Destination>
            value
        </Destination>
    </message>
</root>

您可以使用例如 configparser 读取文件;你可能有更好的方法。

It would be easier to regenerate the XML file than to modify it in place:

from xml.dom.minidom import Document

doc = Document( )
root = doc.createElement( "root" )

for key, value in <some iterator>:
    message = doc.createElement( "message" )

    source = doc.createElement( "Source" )
    source.appendChild( doc.createTextNode( key ) )

    dest = doc.createElement( "Destination" )
    dest.appendChild( doc.createTextNode( value ) )

    message.appendChild( source )
    message.appendChild( dest )
    root.appendChild( message )

doc.appendChild( root )

print( doc.toprettyxml( ) )

This will print:

<root>
    <message>
        <Source>
            key
        </Source>
        <Destination>
            value
        </Destination>
    </message>
</root>

You could use e.g. configparser to read the file; you may have a better way.

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