我试着用下面的代码生成一个包含标签</documents>的XML文件。
string = "dasdd Wonder asdf new single, “Tomorrow” #URL# | " \
"oiojk asfddsf releases new asdfdf, “gfsg” | " \
"Identity of asfqw who dasd off asdfsdf Mainland jtyjyjui revealed #URL#"
from yattag import Doc, indent
import html, re
doc, tag, text = Doc().tagtext()
with tag('author', lang='en'):
with tag('documents'):
for tweet in string.split(' | '):
with tag('document'):
tweet = html.unescape(tweet)
text('<![CDATA[{}]]'.format(tweet))
result = indent(doc.getvalue(), indentation=' ' * 4, newline='\n')
with open('test.xml', 'w', encoding='utf-8') as f:
f.write(result)我想在文本周围添加CDATA标记,但是当我使用Notepad++打开生成的文件时,而不是像下面这样输出:
<document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]></document>它看起来像(带有HTML实体):
<document><![CDATA[oiojk asfddsf releases new asdfdf, “gfsg”]]</document>我尝试使用HTML库(html.unescape行)来丢弃HTML实体,但是我不能。
如何解决这个编码问题?
发布于 2020-02-18 00:24:21
text方法总是用<替换'<‘。如果您不想进行这种转义,那么可以使用asis方法(它会按原样插入字符串)。但是,在您的示例中,使用Yattag的cdata方法会更合适。
from yattag import Doc
help(Doc.cdata)cdata(self,strg,safe=False)附加一个包含所提供字符串的CDATA节。
您不必担心会终止CDATA部分的潜在]]>序列。它们被]]]]><![CDATA[>所取代。
如果你确定你的字符串不包含]]>,你可以传递safe = True。如果这样做,就不会在您的字符串中搜索]]>序列。
因此,在您的情况下,您可以这样做:
for tweet in string.split(' | '):
with tag('document'):
tweet = html.unescape(tweet)
doc.cdata(tweet)https://stackoverflow.com/questions/60264602
复制相似问题