Validador XML
Valide documentos XML com suporte para DTD e schemas XSD
What is XML Validation?
XML validation is the process of checking whether an XML document conforms to the structural and syntactical rules defined by the XML 1.0 specification. Unlike formatting β which adjusts indentation and whitespace for human readability β validation answers a critical question: is this document well-formed XML that any conforming parser can process without errors? XML validation operates at multiple levels: well-formedness checking verifies that the document follows the basic XML grammar rules, while schema validation (DTD, XSD, or RELAX NG) verifies that the document structure matches a predefined contract. This tool performs well-formedness validation with detailed error reporting including line numbers, column positions, and diagnostic descriptions to help you locate and resolve problems before they cause integration failures or data loss.
Well-Formedness Rules: The Foundation of XML Validity
The W3C XML 1.0 specification defines strict well-formedness constraints that every XML document must satisfy. A document that violates any of these rules is not XML β parsers are required to report a fatal error and stop processing. There is no concept of "partially valid" XML; the document either passes all well-formedness checks or it is rejected entirely:
- Single root element: Every XML document must contain exactly one root element
that encloses all other content. Multiple root elements (e.g., two sibling
<div>elements at the top level) violate the document structure requirement. This is distinct from HTML where fragments are tolerated β in XML, the single-root rule is absolute. - Proper element nesting: Opening and closing tags must nest correctly without
overlap.
<a><b></a></b>is malformed because the<b>element is not properly closed before<a>ends. Every opening tag must have a corresponding closing tag at the correct nesting depth, or the element must use the self-closing syntax<element/>. - Case-sensitive tag matching: XML is case-sensitive β
<Item>and<item>are different elements. A closing tag must match its opening tag in exact case. This catches errors that would be silently accepted in case-insensitive HTML parsing. - Attribute quoting: All attribute values must be enclosed in either single
or double quotes. Unquoted attributes like
<div class=main>are valid in HTML5 but produce a fatal error in XML. Every attribute must use thename="value"orname='value'syntax. - No duplicate attributes: An element cannot have two attributes with the
same name.
<div class="a" class="b">is well-formedness violation that parsers must reject, even though browsers silently ignore the duplicate in HTML mode. - Proper entity references: The characters
<,&, and in certain contexts"and'must be escaped using predefined entity references (<,&,",'). A bare ampersand or less-than sign in text content is a fatal parsing error. - Valid XML declaration: If present, the XML declaration
(
<?xml version="1.0" encoding="UTF-8"?>) must be the very first content in the document β no whitespace, no BOM without declaration, no comments before it.
Well-Formedness vs Schema Validation: Two Levels of Checking
XML validation operates at two distinct levels that address different concerns. Understanding the difference is essential for choosing the right validation approach for your use case:
Well-formedness checking verifies that the document is syntactically correct XML. It answers: "Can any XML parser read this without crashing?" Well-formedness constraints are defined by the XML 1.0 specification itself and are universal β they apply to every XML document regardless of its purpose. A well-formed document has properly nested elements, quoted attributes, escaped special characters, and a single root element. This is what this tool validates.
Schema validation verifies that the document structure conforms to a predefined
contract. It answers: "Does this document contain the expected elements and attributes in the
correct arrangement?" Schema validation requires a reference schema written in DTD (Document
Type Definition), XML Schema Definition (XSD), or RELAX NG format. For example, a schema might
require that a <person> element always contains a <name>
child and an optional <email> child with a specific format constraint.
The relationship between these levels is hierarchical: a document must be well-formed before schema validation can even begin. If the parser cannot build a tree from the raw text (due to mismatched tags or unescaped characters), there is no structure to validate against a schema. In practice, most integration errors stem from well-formedness violations rather than schema mismatches, because well-formedness errors prevent any processing whatsoever.
Common schema validation scenarios include SOAP web service messages (validated against WSDL/XSD), SVG graphics (validated against the SVG DTD), XHTML documents (validated against the XHTML DTD), and industry-specific formats like HL7 CDA (healthcare), FIXML (finance), and UBL (e-invoicing). Each domain defines schemas that constrain element names, attribute values, cardinality, and ordering beyond what well-formedness alone guarantees.
Common XML Errors and How to Detect Them
XML's strictness compared to HTML means that errors which browsers silently handle will cause XML parsers to halt with a fatal error. Understanding the most common mistakes helps you write correct XML and interpret validator error messages effectively:
Unclosed or mismatched tags: The most frequent XML error. Every
<tag> needs a corresponding </tag>, and self-closing
elements must use <tag/> syntax. Unlike HTML where <br>
or <img> are valid void elements, XML requires explicit closure for every
element without exception.
Unescaped ampersands and less-than signs: Text content like
price < 100 or AT&T must use entity references:
price < 100 and AT&T. This is particularly common
when embedding URLs with query parameters (¶m=value) or mathematical
expressions. CDATA sections (<![CDATA[...]]>) provide an alternative for
content with many special characters.
Invalid characters in element names: XML element names must start with a letter
or underscore, and cannot contain spaces, start with digits, or include characters like
/, +, or =. Names like <2ndItem>
or <my element> are invalid. The colon character is reserved exclusively
for namespace prefixes.
Namespace errors: When elements use prefixed names like
<soap:Envelope>, the namespace prefix must be declared via an
xmlns:soap attribute on that element or an ancestor. Using an undeclared prefix
is a namespace well-formedness error. Additionally, the default namespace
(xmlns="...") does not apply to attributes β a common source of confusion when
working with namespaced XML vocabularies.
Encoding mismatches: If the XML declaration states
encoding="UTF-8" but the file actually contains ISO-8859-1 byte sequences, the
parser encounters invalid byte sequences and reports a fatal error. This commonly happens
when copying content between systems with different default encodings, or when text editors
save files in an encoding different from what the XML declaration claims.
XML Namespaces and Validation Challenges
XML Namespaces add a layer of complexity to validation that deserves separate attention. Namespaces prevent element name collisions when combining vocabularies from different sources β for example, an XSLT stylesheet that contains both XSLT instructions and HTML output elements. However, they introduce their own class of well-formedness errors:
Undeclared namespace prefixes: Every prefixed element or attribute
(e.g., xsl:template) must have a corresponding namespace declaration
(xmlns:xsl="http://www.w3.org/1999/XSL/Transform") in scope. A validator
detects uses of undeclared prefixes that would cause a namespace-aware parser to reject
the document.
The xml prefix is reserved: The prefix xml is
permanently bound to http://www.w3.org/XML/1998/namespace and cannot be
redeclared. Similarly, xmlns is reserved for namespace declarations themselves.
Attempting to use these prefixes for other URIs is a namespace constraint violation.
Default namespace behavior: The default namespace (declared with
xmlns="...") applies to the element and all unprefixed descendant elements,
but it does not apply to attributes. This distinction means that
<element xmlns="urn:example" attr="value"> places element
in the namespace urn:example, but attr has no namespace. This
is a frequent source of bugs in SOAP messages and SVG documents where developers expect
attributes to inherit the default namespace.
Namespace-aware validation is critical for interoperability. Web services (SOAP, REST with XML), document formats (SVG, MathML, XHTML), and enterprise integrations (EDI, HL7) all rely on correct namespace usage. A missing or incorrect namespace declaration can cause an otherwise structurally correct document to be rejected by the receiving system because elements are not recognized as belonging to the expected vocabulary.
Code Examples
XML well-formedness validation with error detection
function validateXml(xmlString) {
const parser = new DOMParser();
const doc = parser.parseFromString(xmlString, 'application/xml');
// DOMParser signals errors via a <parsererror> element
const parseError = doc.querySelector('parsererror');
if (parseError) {
// Extract error details from the parsererror content
const errorText = parseError.textContent || 'Unknown parse error';
const lineMatch = errorText.match(/line (\d+)/i);
const colMatch = errorText.match(/column (\d+)/i);
return {
valid: false,
error: errorText,
line: lineMatch ? parseInt(lineMatch[1], 10) : undefined,
column: colMatch ? parseInt(colMatch[1], 10) : undefined,
};
}
return { valid: true, rootElement: doc.documentElement.tagName };
}
// β
Valid XML
validateXml('<root><item id="1">Hello</item></root>');
// β { valid: true, rootElement: "root" }
// β Mismatched tags
validateXml('<root><item>text</items></root>');
// β { valid: false, error: "...mismatched tag...", line: 1, column: 23 }
// β Unquoted attribute
validateXml('<root><item id=123>text</item></root>');
// β { valid: false, error: "...attribute value...", line: 1, column: 15 }
// β Unescaped ampersand
validateXml('<root><name>AT&T</name></root>');
// β { valid: false, error: "...not well-formed...", line: 1, column: 16 }Output:
{ valid: true, rootElement: "root" }
{ valid: false, error: "mismatched tag. Expected </item>", line: 1, column: 23 }
{ valid: false, error: "attribute value expected", line: 1, column: 15 }
{ valid: false, error: "not well-formed", line: 1, column: 16 }Standards & Specifications
- W3C XML 1.0 Specification (Fifth Edition) β The normative specification defining XML well-formedness constraints and grammar rules enforced by this validator
- Namespaces in XML 1.0 (Third Edition) β The W3C specification for XML namespace syntax and namespace-aware well-formedness constraints