lxml 追加数组元素 python3.6

lxml append array element python3.6

我正在构建 xml 格式。

我想做这样的事情:

<ValidationRequest>
<Username>admin@xgateinternal.com</Username>
<Password>XBR!t6YMeJbmsjqV</Password>
<Email>12345@gmail.com</Email>
<Email>564685@yahoo.com.hk</Email>
<Email>54321@yahoo.com.hk</Email>
</ValidationRequest>

现在我可以将所有电子邮件附加到 ValidationRequest 中。但是我弄错格式了。

这是我的代码:

#!/usr/bin/python
import lxml.etree
import lxml.builder    

email = ['12345@gmail.com','564685@yahoo.com.hk','54321@yahoo.com.hk']

E = lxml.builder.ElementMaker()
ValidationRequest = E.ValidationRequest
Username = E.Username
Password = E.Password
Email = E.Email

op = []
for a in email:
    GG = Email(a)
    op.append(lxml.etree.tostring(GG, pretty_print=True))
    print (lxml.etree.tostring(GG, pretty_print=True))
print(op)
ed = ''.join(map(str, op))
print(ed)
the_doc = ValidationRequest(
            Username('admin'),
            Password('XBR'),
            ed
        )   

print (lxml.etree.tostring(the_doc, pretty_print=True))

回复:

b'<Email>12345@gmail.com</Email>\n'
b'<Email>564685@yahoo.com.hk</Email>\n'
b'<Email>54321@yahoo.com.hk</Email>\n'
[b'<Email>12345@gmail.com</Email>\n', b'<Email>564685@yahoo.com.hk</Email>\n', b'<Email>54321@yahoo.com.hk</Email>\n']
b'<Email>12345@gmail.com</Email>\n'b'<Email>564685@yahoo.com.hk</Email>\n'b'<Email>54321@yahoo.com.hk</Email>\n'
b"<ValidationRequest><Username>admin</Username><Password>XBR</Password>b'&lt;Email&gt;12345@gmail.com&lt;/Email&gt;\n'b'&lt;Email&gt;564685@yahoo.com.hk&lt;/Email&gt;\n'b'&lt;Email&gt;54321@yahoo.com.hk&lt;/Email&gt;\n'</ValidationRequest>\n"

如何将 和 post 保存到 ValidationRequest?

你的想法是对的,那里有很多东西只是在四处移动。你可以把它归结为:

import lxml.etree
import lxml.builder

email = ['12345@gmail.com','564685@yahoo.com.hk','54321@yahoo.com.hk']

em = lxml.builder.ElementMaker()

the_doc = em.ValidationRequest(
    em.Username('admin'),
    em.Password('XBR'),
    *(em.Email(address) for address in email)
)

print(lxml.etree.tostring(the_doc, pretty_print=True).decode())

.decode() 只是为了打印得好。如果您需要 bytes,您可以将其关闭。

特别注意这一行:

    *(em.Email(address) for address in email)

这遍历 email,为每个地址生成一个 Email 元素,然后将生成的元组(生成器周围括号的结果)解包到ValidationRequest 元素的构造函数。

输出:

<ValidationRequest>
  <Username>admin</Username>
  <Password>XBR</Password>
  <Email>12345@gmail.com</Email>
  <Email>564685@yahoo.com.hk</Email>
  <Email>54321@yahoo.com.hk</Email>
</ValidationRequest>