Parsing XML file does not yield default values from schema

I’m thinking that PHP is the proper place for this post, but it may be related to my lapse in XML schema definitions that is the problem.
I’ll try posting minimal portions of the XML and XSD for readability, but can post more if needed.

I have a schema with a default value for one of it’s elements

<xsd:element name="language" type="xsd:string" minOccurs="0" default="EN" />

So my XML file might look like

<book id="1">
  <title>A Tale of Two Cities</title>
<book id="2">
  <title>The Hunchback of Notre Dame</title>

The PHP looks like:

$file = "filename.xml";
if(file_exists($file) && ($xml = simplexml_load_file($file)))
	foreach($xml->children() as $book)
		foreach($book->children() as $attrib)
			echo("<p>Book " . $book['id'] . ": " . $attrib->getName() . "='" . $attrib . "'</p>");
	echo("<h1>Error reading '" . $file . "'<br />");

The webpage looks like

[INDENT]Book 1: title=‘A Tale of Two Cities’
Book 2: language=‘FR’
Book 2: title=‘The Hunchback of Notre Dame’
I’m expecting, but not getting:

[INDENT]Book 1: language=‘EN’
Where have I gone wrong?
p.s. Same results using XML DOM vs simplexml.

Hi canufrank, welcome to the forums,

AFAIK neither XML DOM nor simplexml automatically grab default values from the XSD - but naybe they do.

minOccurs = 0
default = En

Maybe if you change minOccurs to 1 it will load the value into the DOM ?

Other than that you could write the default into the PHP code I suppose.

Changing minOccurs to 1, or just omitting it, would (IMHO) defeat the purpose of using default. The XML file would then be invalid unless the author included the - supposedly defaulted - language element.

I believe that I am either implementing or understanding the concept incorrectly. :frowning: Is there another parser that will allow me access to the default values?

I have written the default into the PHP, but hard-coding it seems like a horrible solution. If the XSD author changes the schema, the PHP author would not know unless it was parsed separately from the XML and I wonder if that is the only solution?

Yes, hard-coding into the PHP code is definately not the best way.

Maybe SDO XML Data Access Service ??