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

2024-10-01 02:32:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须生成如下的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>

我一直在尝试的代码(下面)生成的一切都很好,但我不能为节点和网络接口设置属性值。 我需要<node name="node1">而不是<node>和{}而不是{}。我尝试在节点和网络接口的括号中添加属性,但python似乎不接受。在

ElementMaker不接受传递给head的属性。这样做的合适语法是什么?怎么可能实现呢?在

代码:

^{pr2}$

Tags: namenode属性serviceconfigurationhostnamenode1ffff
1条回答
网友
1楼 · 发布于 2024-10-01 02:32:24

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

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")
)

或通过字典提供属性:

^{pr2}$

相关问题 更多 >