Dmitry
Dmitry

Reputation: 21

How to merge 2 xsd schema

I have 2 xsd schema which I need to merge F.e.

<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:complexType name="UserType">
            <xs:sequence>
                <xs:element type="xs:string" name="Field1"/>
                <xs:element type="xs:string" name="Field6"/>
            </xs:sequence>
        </xs:complexType>
    </xs:schema>

<?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <xsd:complexType name="UserType">
            <xsd:sequence>
                <xsd:element type="xsd:string" name="Field1"/>
                <xsd:element type="xsd:string" name="Field2"/>
                <xsd:element type="xsd:string" name="Field3"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:schema>

I try merge there and write next code that merge 2 xsd files into one and print result.

$DOMChild = new \DOMDocument;
$DOMChild->loadXML($child);
$node = $DOMChild->documentElement;

$DOMParent = new \DOMDocument;
$DOMParent->formatOutput = true;
$DOMParent->loadXML($parent);

$node = $DOMParent->importNode($node, true);

if ($tag !== null) {
    $tag = $DOMParent->getElementsByTagName($tag)->item(0);
    $tag->appendChild($node);
} else {
    $DOMParent->documentElement->appendChild($node);
}

echo $DOMParent->saveXML();

Result of it the next:

<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:complexType name="UserType">
            <xs:sequence>
                <xs:element type="xs:string" name="Field1"/>
                <xs:element type="xs:string" name="Field6"/>
            </xs:sequence>
        </xs:complexType>
        <xs:schema>
            <xs:complexType name="UserType">
            <xs:sequence>
                <xsd:element type="xsd:string" name="Field1"/>
                <xsd:element type="xsd:string" name="Field2"/>
                <xsd:element type="xsd:string" name="Field3"/>
            </xs:sequence>
        </xs:complexType>
        </xs:schema>
    </xs:schema>

I dont need parse from child file to parent node but I dont'n know how it can be deleted from result file.

Could someone help me?! Thank you

Upvotes: 1

Views: 586

Answers (1)

Dmitry
Dmitry

Reputation: 21

It seems I found the solution

$first = new \DOMDocument("1.0", 'UTF-8');
$first->formatOutput = true;
$first->loadXML($parent);

$second = new \DOMDocument("1.0", 'UTF-8');
$second->formatOutput = true;
$second->loadXML($child);
$second = $second->documentElement;

foreach($second->childNodes as $node)
{
    $importNode = $first->importNode($node,TRUE);
    $first->documentElement->appendChild($importNode);
}
echo $first->saveXML();

Upvotes: 1

Related Questions