问题描述
我正在使用ElementTree API读取和写入XML文档.当我尝试添加以数字开头的标签时,XML文件不再有效.使用 import xml.etree.cElementTree作为ET
,我能够成功创建XML文档,但是当我尝试再次读取XML文件时,出现了ParseError.就我的目的而言,XML文档的格式是否正确并不重要.我只需要能够以数字开头的标签.您知道如何执行此操作吗?
I'm using ElementTree API to read and write to an XML document. When I try to add a tag that starts with a number, the XML file is no longer valid. Using import xml.etree.cElementTree as ET
, I am successfully able to create the XML document, but when I try to read in the XML file again, I get a ParseError. For my purposes, it does not matter if the XML document is not well formed. I just need to be able to start a tag with a number. Any idea how to do this?
这是我尝试过的:
from lxml import etree
parser = etree.XMLParser(recover=True)
tree = ET.parse('xmldoc.xml')
root = tree.getroot()
xmlstring = ET.tostring(root)
etree.fromstring(xmlstring, parser=parser)
如果我使用它,则会出现此错误:
If I use this, I get this error:
尝试执行此操作后:
inputowner = raw_input("Enter owner for " + ls[i] + ": ")
child = ET.SubElement(prev , ls[i], owner = inputowner)
prev = child
prevowner = inputowner
这是我要放入XML文件中的列表:
Here is the list I am trying to put into an XML file:
['components', 'rel', 'core.slpi', '1.0', 'blluuses', 'i2c', 'src', 'logs', 'I2cUlog.c']
列表中的每个项目都应用作ElementTree标记.当我达到"1.0"时就会出现问题.
Each item in the list should be used as the ElementTree tag. The problem arises when I reach '1.0'.
如果无法回答第一个问题,您是否知道其他模块几乎可以做同样的事情,但允许我使用以数字开头的标签?ElementTree太棒了,我只需要一件事情就能工作,然后我就可以继续了.
If unable to answer first question, do you know of any other module that will do virtually the same thing but allow me have a tag that starts with a number? ElementTree is fantastic, I just need this one thing to work and then I can move on.
推荐答案
STag ::= '<' Name (S Attribute)* S? '>'
Name ::= NameStartChar (NameChar)*
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
如果文件具有以数字开头的标签,则该文件不是XML文档.为了创建这样的文件, 不要期望任何兼容的XML库提供支持 .为了创建带有以数字开头的标签的文件,您必须在文本级别进行操作,但是,实际上,最好不要违反常规-只需以字母开头标签即可,以便您可以利用在 格式正确的XML 上运行的工具.
If a file has a tag that begins with a number, then the file is not an XML document. In order to create such a file, do not expect support from any conformant XML library. In order to create a file with tags that started with numbers, you'd have to operate at the text level, but, really, you're better not going against the grain -- just start your tags with letters so that you can leverage tools that operate on well-formed XML.
这篇关于如何使XML标签以数字开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!