
我当前正在使用 lxml 并希望验证 xml 内容。
我从 tei = etree.element("tei", nsmap={none: 'http://www.tei-c.org/ns/1.0'} 完全用 python 编写,包含许多子元素。 p>
现在,我想使用以下代码使用特定的 .xsd 文件检查结构是否正确:
xmlschema_doc = etree.parse(xsd_file_path) xmlschema = etree.xmlschema(xmlschema_doc) # run check status = xmlschema.validate(xml_tree)
它返回 false,并显示错误 element 'tei':没有可用于验证 root. 的匹配全局声明
我观察到一件非常奇怪的事情,如果我使用 编写 xml
et = etree.elementtree(xmldata)
et.write('test.xml', pretty_print=true, xml_declaration=true, encoding='utf-8')
如果我用 b= etree.parse('test.xml') 重新打开它,我最终没有错误,并且由于 xmlschema.validate(b) 的结果,xml 结构是有效的
知道我需要在 xml 结构中添加什么吗?
编辑: 无效 xml 中的第一项
有效 xml 文件中的第一项
编辑:
article article A subtitle John Doe orcid Jane Middle Doe orcid small comment small description article article A subtitle John Doe orcid Jane Middle Doe orcid 978-1725183483 117751 xxx springer a special collection 20 1 10-25 2024-01-01 reg ger erg greger greger gaergezg gegzefdv vvxc gderg gev xcvcxv vxcv https://publisher.com/ID https://link1.com/ID https://link2.com/ID https://link3.com/IDkeyword1 keyword2 mot-clé1 mot-clé2 laboratory for MC, university of Yeah LMC Blue street 155, 552501 Olso, Norway Lesotho laboratory for MCL, university of Yeah LMCL Blue street 155, 552501 Olso, Norway Norway
正确答案
看看https://www.php.cn/link/e1ff36b97044a1c7c73c73e4d27aeba4,你基本上应该使用
tei_namespace = "http://www.tei-c.org/ns/1.0"
tei = "{%s}" % tei_namespace
nsmap = {none : tei_namespace} # the default namespace (no prefix)
root = etree.element(tei + "tei", nsmap=nsmap) # lxml only!
text = etree.subelement(root, tei + "text")
对所有元素依此类推,以确保它们是在 tei 命名空间中创建的。
在内存中创建的 elementtree 对架构有效(在我将其与导入的 w3c xml.xsd 一起下载后)是例如
from lxml import etree
TEI_NAMESPACE = "http://www.tei-c.org/ns/1.0"
TEI = "{%s}" % TEI_NAMESPACE
NSMAP = {None : TEI_NAMESPACE} # the default namespace (no prefix)
root = etree.Element(TEI + "TEI", nsmap=NSMAP) # lxml only!
text = etree.SubElement(root, TEI + "text")
body = etree.SubElement(text, TEI + "body")
listBibl = etree.SubElement(body, TEI + "listBibl")
biblFull = etree.SubElement(listBibl, TEI + "biblFull")
sourceDesc = etree.SubElement(biblFull, TEI + "sourceDesc")
profileDesc = etree.SubElement(biblFull, TEI + "profileDesc")
xmlschema_doc = etree.parse("aofr.xsd")
xmlschema = etree.XMLSchema(xmlschema_doc)
# run check
status = xmlschema.validate(root)
print(status)
print(xmlschema.error_log)










