gpt4 book ai didi

python - 检查 XML 声明是否存在

转载 作者:行者123 更新时间:2023-12-04 17:40:17 25 4
gpt4 key购买 nike

我正在尝试检查 xml 文件是否包含必要的 xml 声明(“ header ”),比方说:

<?xml version="1.0" encoding="UTF-8"?>
...rest of xml file...

我正在使用 xml ElementTree 来读取文件并从文件中获取信息,但它似乎可以很好地加载文件,即使它没有标题。

到目前为止我尝试的是:

import xml.etree.ElementTree as ET
tree = ET.parse(someXmlFile)

try:
xmlFile = ET.tostring(tree.getroot(), encoding='utf8').decode('utf8')
except:
sys.stderr.write("Wrong xml2 header\n")
exit(31)

if re.match(r"^\s*<\?xml version=\'1\.0\' encoding=\'utf8\'\?>\s+", xmlFile) is None:
sys.stderr.write("Wrong xml1 header\n")
exit(31)

但是如果文件中不存在 ET.tostring() 函数只是“组成”一个 header 。

有什么方法可以用 ET 检查 xml header 吗?或者如果文件不包含 xml header ,则在使用 ET.parse 加载文件时以某种方式抛出错误?

最佳答案

tl;dr

from xml.dom.minidom import parseString
def has_xml_declaration(xml):
return parseString(xml).version

来自 Wikipedia's XML declaration

If an XML document lacks encoding specification, an XML parser assumes that the encoding is UTF-8 or UTF-16, unless the encoding has already been determined by a higher protocol.

...

The declaration may be optionally omitted because it declares as its encoding the default encoding. However, if the document instead makes use of XML 1.1 or another character encoding, a declaration is necessary. Internet Explorer prior to version 7 enters quirks mode, if it encounters an XML declaration in a document served as text/html

因此,即使在 XML 文档中省略了 XML 声明,代码片段:

if re.match(r"^<\?xml\s*version=\'1\.0\' encoding=\'utf8\'\s*\?>", xmlFile.decode('utf-8')) is None:

将在此 XML 文档中找到“the”默认 XML 声明。请注意,我使用了 xmlFile.decode('utf-8') 而不是 xmlFile。如果你不担心使用 minidom,你可以使用下面的代码片段:

from xml.dom.minidom import parse

dom = parse('bookstore-003.xml')
print('<?xml version="{}" encoding="{}"?>'.format(dom.version, dom.encoding))

这是一个有效的 fiddleInt bookstore-001.xml 存在 XML 声明,在 bookstore-002.xml 中不存在 XML 声明,在 bookstore-003.xml 中存在与第一个示例不同的 XML 声明。 print 指令打印相应的版本和编码:

<?xml version="1.0" encoding="UTF-8"?>

<?xml version="None" encoding="None"?>

<?xml version="1.0" encoding="ISO-8859-1"?>

关于python - 检查 XML 声明是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54825048/

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