gpt4 book ai didi

python - 如何使用 ElementMaker 向元素添加属性?

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:51 27 4
gpt4 key购买 nike

我必须生成如下 XML,

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<serviceConfiguration xmlns="http://blah.com/serviceConfiguration">
<node name="node1">
<hostName>host1</hostName>
<networkInterface name="eth0">
<ipv4Address>192.168.1.3</ipv4Address>
<ipv6Address>2a00:4a00:a000:11a0::a4f:3</ipv6Address>
<domainName>asdf.net</domainName>
<ipv4Netmask>255.255.255.0</ipv4Netmask>
<ipv6Netmask>ffff:ffff:ffff:ffff::</ipv6Netmask>
</networkInterface>
<userAccount>
<uid>root</uid>
<uidNumber>0</uidNumber>
<gidNumber>0</gidNumber>
<homeDirectory>/root</homeDirectory>
<publicKey>
<key/>
<algorithm>RSA</algorithm>
</publicKey>
</userAccount>
</node>
</serviceConfiguration>

我一直在尝试的代码(如下)生成一切正常,但我无法设置节点和网络接口(interface)的属性值。我需要<node name="node1">而不是<node><networkInterface name="eth0">而不是<networkInterface> 。我尝试在节点和网络接口(interface)的括号中添加属性,但 python 似乎不接受它。

ElementMaker 不接受传递给 head 的属性。执行此操作的适当语法是什么?怎么可能实现?

代码:

from lxml import etree
from lxml.builder import ElementMaker

E = ElementMaker(namespace="http://blah.com/serviceConfiguration", nsmap={None: "http://blah.com/serviceConfiguration"})

SC = E.serviceConfiguration
NODE = E.node
HN = E.hostName
NI = E.networkInterface
I4 = E.ipv4Address
I6 = E.ipv6Address
DN = E.domainName
I4N = E.ipv4Netmask
I6N = E.ipv6Netmask
UA = E.userAccount
UI = E.uid
UIN = E.uidNumber
GIN = E.gidNumber
HD = E.homeDirectory
PK = E.publicKey
K = E.key
A = E.algorithm

my_doc = SC(
NODE(
HN('host1'),
NI(
I4('ipv4Address'),
I6('ipv6Address'),
DN('domainName'),
I4N('ipv4Netmask'),
I6N('ipv6Netmask')
),
UA(
UI('uid'),
UIN('uidNumber'),
GIN('gidNumber'),
HD('homeDirectory'),
PK(
K('key'),
A('algorithm')
)
)
)
)

print(etree.tostring(my_doc, encoding="UTF-8", standalone="yes", pretty_print=True))

最佳答案

在子元素后面添加属性作为关键字参数:

my_doc = SC(
NODE(
HN('host1'),
NI(
I4('ipv4Address'),
I6('ipv6Address'),
DN('domainName'),
I4N('ipv4Netmask'),
I6N('ipv6Netmask'),
name="eth0"),
UA(
UI('uid'),
UIN('uidNumber'),
GIN('gidNumber'),
HD('homeDirectory'),
PK(
K('key'),
A('algorithm')
)
),
name="node1")
)

或者通过字典提供属性:

my_doc = SC(
NODE({'name': 'node1'},
HN('host1'),
NI(
I4('ipv4Address'),
I6('ipv6Address'),
DN('domainName'),
I4N('ipv4Netmask'),
I6N('ipv6Netmask'),
name="eth0"),
UA(
UI('uid'),
UIN('uidNumber'),
GIN('gidNumber'),
HD('homeDirectory'),
PK(
K('key'),
A('algorithm')
)
)
)
)

关于python - 如何使用 ElementMaker 向元素添加属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com