How to have an XML tag start with a number?

假装没事ソ 提交于 2021-02-16 19:13:31

问题


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?

This is what I have tried:

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:

ValueError: Invalid tag name u'1.0'

after trying to do this:

            inputowner = raw_input("Enter owner for " + ls[i] + ": ")
            child = ET.SubElement(prev , ls[i], owner = inputowner)
            prev = child
            prevowner = inputowner

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']

Each item in the list should be used as the ElementTree tag. The problem arises when I reach '1.0'.

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.


回答1:


XML element names cannot begin with a number:

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]

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.



来源:https://stackoverflow.com/questions/31253137/how-to-have-an-xml-tag-start-with-a-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!