search
HomeBackend DevelopmentPython TutorialUnable to validate XML using schema, but works by reading file written from

无法使用架构验证 XML,但可以通过从中读取写入的文件来工作

Question content

I am currently using lxml and want to validate the xml content.

I started from tei = etree.element("tei", nsmap={none: 'http://www.tei-c.org/ns/1.0'} Completely written in python, including Many child elements. p>

Now, I want to check if the structure is correct using a specific .xsd file using the following code:

xmlschema_doc = etree.parse(xsd_file_path)
xmlschema = etree.xmlschema(xmlschema_doc)
# run check
status = xmlschema.validate(xml_tree)

It returns false with error element 'tei': No matching global declaration available to verify root.

I observed a very strange thing, if I write xml using

et = etree.elementtree(xmldata)
et.write('test.xml', pretty_print=true, xml_declaration=true, encoding='utf-8')

If I reopen it with

b= etree.parse('test.xml') I end up with no errors, and as a result of xmlschema.validate(b), The xml structure is valid

Any idea what I need to add in the xml structure?

edit: Invalid first item in xml

The first item in a valid xml file

edit:

<?xml version='1.0' encoding='UTF-8'?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
  <text>
    <body>
      <listBibl>
        <biblFull>
          <titleStmt>
            <title xml:lang="en">article</title>
            <title xml:lang="fr">article</title>
            <title type="sub" xml:lang="en">A subtitle</title>
            <author role="aut">
              <persName>
                <forename type="first">John</forename>
                <surname>Doe</surname>
              </persName>
              <email>email</email>
              <idno type="http://orcid.org/">orcid</idno>
              <affiliation ref="#localStruct-affiliation"/>
              <affiliation ref="#struct-affiliation"/>
            </author>
            <author role="aut">
              <persName>
                <forename type="first">Jane</forename>
                <forename type="middle">Middle</forename>
                <surname>Doe</surname>
              </persName>
              <email>email</email>
              <idno type="http://orcid.org/">orcid</idno>
              <affiliation ref="#localStruct-affiliationA"/>
              <affiliation ref="#localStruct-affiliationB"/>
            </author>
          </titleStmt>
          <editionStmt>
            <edition>
              <ref type="file" subtype="author" n="1" target="upload.pdf"/>
            </edition>
          </editionStmt>
          <publicationStmt>
            <availability>
              <licence target="https://creativecommons.org/licenses//cc-by/"/>
            </availability>
          </publicationStmt>
          <notesStmt>
            <note type="audience" n="2"/>
            <note type="invited" n="1"/>
            <note type="popular" n="0"/>
            <note type="peer" n="1"/>
            <note type="proceedings" n="0"/>
            <note type="commentary">small comment</note>
            <note type="description">small description</note>
          </notesStmt>
          <sourceDesc>
            <biblStruct>
              <analytic>
                <title xml:lang="en">article</title>
                <title xml:lang="fr">article</title>
                <title type="sub" xml:lang="en">A subtitle</title>
                <author role="aut">
                  <persName>
                    <forename type="first">John</forename>
                    <surname>Doe</surname>
                  </persName>
                  <email>email</email>
                  <idno type="http://orcid.org/">orcid</idno>
                  <affiliation ref="#localStruct-affiliation"/>
                  <affiliation ref="#struct-affiliation"/>
                </author>
                <author role="aut">
                  <persName>
                    <forename type="first">Jane</forename>
                    <forename type="middle">Middle</forename>
                    <surname>Doe</surname>
                  </persName>
                  <email>email</email>
                  <idno type="http://orcid.org/">orcid</idno>
                  <affiliation ref="#localStruct-affiliationA"/>
                  <affiliation ref="#localStruct-affiliationB"/>
                </author>
              </analytic>
              <monogr>
                <idno type="isbn">978-1725183483</idno>
                <idno type="halJournalId">117751</idno>
                <idno type="issn">xxx</idno>
                <imprint>
                  <publisher>springer</publisher>
                  <biblScope unit="serie">a special collection</biblScope>
                  <biblScope unit="volume">20</biblScope>
                  <biblScope unit="issue">1</biblScope>
                  <biblScope unit="pp">10-25</biblScope>
                  <date type="datePub">2024-01-01</date>
                </imprint>
              </monogr>
              <series/>
              <idno type="doi">reg</idno>
              <idno type="arxiv">ger</idno>
              <idno type="bibcode">erg</idno>
              <idno type="ird">greger</idno>
              <idno type="pubmed">greger</idno>
              <idno type="ads">gaergezg</idno>
              <idno type="pubmedcentral">gegzefdv</idno>
              <idno type="irstea">vvxc</idno>
              <idno type="sciencespo">gderg</idno>
              <idno type="oatao">gev</idno>
              <idno type="ensam">xcvcxv</idno>
              <idno type="prodinra">vxcv</idno>
              <ref type="publisher">https://publisher.com/ID</ref>
              <ref type="seeAlso">https://link1.com/ID</ref>
              <ref type="seeAlso">https://link2.com/ID</ref>
              <ref type="seeAlso">https://link3.com/ID</ref>
            </biblStruct>
          </sourceDesc>
          <profileDesc>
            <textClass>
              <keywords scheme="author">
                <term xml:lang="en">keyword1</term>
                <term xml:lang="en">keyword2</term>
                <term xml:lang="fr">mot-clé1</term>
                <term xml:lang="fr">mot-clé2</term>
              </keywords>
              <classCode scheme="halDomain" n="physics"/>
              <classCode scheme="halDomain" n="halDomain2"/>
              <classCode scheme="halTypology" n="ART"/>
            </textClass>
          </profileDesc>
        </biblFull>
      </listBibl>
    </body>
    <back>
      <listOrg type="structures">
        <org type="institution" xml:id="localStruct-affiliation">
          <orgName>laboratory for MC, university of Yeah</orgName>
          <orgName type="acronym">LMC</orgName>
          <desc>
            <address>
              <addrLine>Blue street 155, 552501 Olso, Norway</addrLine>
              <country key="LS">Lesotho</country>
            </address>
            <ref type="url" target="https://lmc.univ-yeah.com"/>
          </desc>
        </org>
        <org type="institution" xml:id="localStruct-affiliationB">
          <orgName>laboratory for MCL, university of Yeah</orgName>
          <orgName type="acronym">LMCL</orgName>
          <desc>
            <address>
              <addrLine>Blue street 155, 552501 Olso, Norway</addrLine>
              <country key="NO">Norway</country>
            </address>
            <ref type="url" target="https://lmcl.univ-yeah.com"/>
          </desc>
        </org>
      </listOrg>
    </back>
  </text>
</TEI>


Correct answer


Look at

https://www.php.cn/link/e1ff36b97044a1c7c73c73e4d27aeba4, you should basically use

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")

And so on for all elements to ensure they are created in the tei namespace.

The elementtree created in memory valid for the schema (after I downloaded it with the imported w3c xml.xsd) is e.g.

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)

The above is the detailed content of Unable to validate XML using schema, but works by reading file written from. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor