XML validation with SCHEMA [PHP]
I can validate an .xml file with -> schemaValidate(.xsd)
the schema I use is the one below. (I'll put a preview).
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.portalfiscal.inf.br/nfe" xmlns="http://www.portalfiscal.inf.br/nfe" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:editix="http://www.portalfiscal.inf.br/nfe" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:import namespace="http://www.w3.org/2000/09/xmldsig#" schemaLocation="xmldsig-core-schema_v1.01.xsd"/>
<xs:include schemaLocation="tiposBasico_v4.00.xsd"/>
<xs:complexType name="TNFe">
<xs:annotation>
<xs:documentation>Tipo Nota Fiscal Eletr??nica</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element name="infNFe">
<xs:annotation>
<xs:documentation>Informa?�?�es da Nota Fiscal Eletr??nica</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="ide">
<xs:annotation>
<xs:documentation>identifica?�??o da NF-e</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="cUF" type="TCodUfIBGE">
<xs:annotation>
<xs:documentation>C??digo da UF do emitente do Documento Fiscal. Utilizar a Tabela do IBGE.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="cNF">
<xs:annotation>
<xs:documentation>C??digo num?�rico que comp?�e a Chave de Acesso. N??mero aleat??rio gerado pelo emitente para cada NF-e.</xs:documentation>
</xs:annotation>
I would like your help to adapt the code below. If when I find an error I consult access this node: <xs:annotation></xs:documentation>I need this message</xs:annotation> <xs:documentation>
and inform the schema message.
the code that I use:
libxml_use_internal_errors(true);
libxml_clear_errors();
$dom = new DOMDocument('1.0', 'utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = false;
$dom->loadXML($xml, LIBXML_NOBLANKS | LIBXML_NOEMPTYTAG);
libxml_clear_errors();
if (! $dom->schemaValidate($xsd)) {
$errors = [];
foreach (libxml_get_errors() as $error) {
$errors[] = $error->message;
}
throw ValidatorException::xmlErrors($errors);
}
Could you help me?
Answer
Solution:
XML schema validation errors are not intended for non-technical users, so I understand your goals.
However, in general this is a difficult problem to solve. If element B is missing from a sequence [A,B,C], the XML validator will not report 'Element A is missing'. .It will say 'Unexpected element C'.
If you only need to handle problems with the value of an element then the problem is slightly easier. You could extract the element name from the error message and look up the element declaration in the XSD.
But...how do you know that one message in your annotation will cover all possible errors in the XML? Are you just trying to add some background information, in addition to the XML Schema error message?
Source