Magento 2 – Create Custom XML File

magento2validationxml

I'm developing an extension that have custom xml/xsd configuration files. When I'm trying to load extension url, it's giving me following error:

Warning: DOMDocument::schemaValidate(): Invalid Schema source in /var/www/html/mage202/vendor/magento/framework/Config/Dom.php on line 290

Example:

in customconfig.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Ktpl_Customconfig:etc/customconfig.xsd">
    <mynode1>HELLO</mynode1>
    <mynode>HELLO 2</mynode2>
</config>

in customconfig.xsd

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="config">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="mynode1" type="xs:string" maxOccurs="10"/>
                <xs:element name="mynode2" type="xs:string" maxOccurs="10"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

in SchemaLocator.php class

namespace Ktpl\Customconfig\Model\Table;
use Magento\Framework\Module\Dir;

class SchemaLocator implements \Magento\Framework\Config\SchemaLocatorInterface
{
    /**
     * Path to corresponding XSD file with validation rules for merged config
     *
     * @var string
     */
    protected $_schema = null;

    /**
     * Path to corresponding XSD file with validation rules for separate config files
     *
     * @var string
     */
    protected $_perFileSchema = null;

    /**
     * @param \Magento\Framework\Module\Dir\Reader $moduleReader
     */
    public function __construct(\Magento\Framework\Module\Dir\Reader $moduleReader)
    {
        $etcDir = $moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Ktpl_Customconfig');
        $this->_perFileSchema = $etcDir . '/customconfig.xsd';
    }

    /**
     * Get path to merged config schema
     *
     * @return string|null
     */
    public function getSchema()
    {
        return $this->_schema;
    }

    /**
     * Get path to pre file validation schema
     *
     * @return string|null
     */
    public function getPerFileSchema()
    {
        return $this->_perFileSchema;
    }
}

How can I create custom xml file and read data from this custom xml file?

Best Answer

Add this to your constructor:

$this->_schema = $etcDir . '/customconfig.xsd';

Beacause getSchema() now returns null.
That is what DOMDocument::schemaValidate() is complaining about.