gpt4 book ai didi

python - 使用 lxml 设置元素内容会删除尾随空格

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:59 25 4
gpt4 key购买 nike

我目前正在尝试使用lxml library创建一个svg图像。 。但是,我创建了一些 tspace 元素来构造和格式化文本元素中的文本,但如果我尝试将此类 tspace 元素的内容设置为“Hello World”之类的内容,则尾随空格将被删除,并且我得到 <tspace>Hello World</tspace>结果。但我想保留这个空白。

此时值得一提的是,我只能访问 Tree 对象,但不能初始化解析器。因此,如果我必须更改一些解析器标志,我将无法直接访问解析器。以下是我的代码的一个小示例:

#!/usr/bin/env python
import sys, os

class HelloPlugin(inkex.Effect):
def __init__(self):
# Call the base class constructor.
inkex.Effect.__init__(self)

def effect(self):
# Fetch the svg root element (lxml etree element) ...
svg = self.document.getroot()

# ... as well as the image width and height.
width = inkex.unittouu(svg.get('width'))
height = inkex.unittouu(svg.get('height'))
fontSize = 12

# Create a new layer.
layer = inkex.etree.SubElement(svg, 'g')
layer.set(inkex.addNS('label', 'inkscape'), 'Headline Layer')
layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')

# Create the text element, ...
text = inkex.etree.SubElement(layer, inkex.addNS('text','svg'))
text.set('x', str(width / 2 + fontSize))
text.set('y', str(height / 2 + fontSize / 2))

# ... define text style and position ...
style = {
'font-size': str(fontSize)
}

# ... and set the text style.
text.set('style', formatStyle(style))

# Finally create the tspan element.
tspan = inkex.etree.SubElement(text, inkex.addNS('tspan','svg'))
tspan.text = "Hello Plugin "

def main(argv):
cubify = Cubify()
cubify.affect()

if __name__ == "__main__":
main(sys.argv[1:])

所以我的问题是,我必须如何更改上面的示例才能获得 <tspace>Hello Plugin </tspace>而不是<tspace>Hello plugin</tspace>在生成的 svg 文件中。

最佳答案

您可能正在寻找 tail property of XML elementslxml.tree图书馆。以下是文档对此的描述:

However, if XML is used for tagged text documents such as (X)HTML, text can also appear between different elements, right in the middle of the tree:

<html><body>Hello<br/>World</body></html>

Here, the <br/> tag is surrounded by text. This is often referred to as document-style or mixed-content XML. Elements support this through their tail property. It contains the text that directly follows the element, up to the next element in the XML tree:

在您的情况下,tail 的内容是空白。这是一个例子:

import lxml.etree as ET
x = ET.fromstring("<foo> <bar>blah</bar> </foo>")
bar = x.find("bar")
print( repr(bar.tail) )

打印:

'    '

关于python - 使用 lxml 设置元素内容会删除尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755556/

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