tags:

views:

46

answers:

0

Hi all,

Consider that you have an XML document with a schema. You want to add a new element to the xml document, and the schema knows where that element belongs. Are there any libraries out there so that I can say effectively "I want to add a new element 'X' into parent node 'A'" and have the library worry about exactly where it adds that element?

For example given a document:

<?xml version="1.0" encoding="utf-8"?>
<car>
    <make>Ford</make>
    <model>T</model>
    <engine-size>1600</engine-size>
</car>

That satisfys the schema:

<?xml version="1.0" encoding="utf-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">

    <xs:complexType name="CarType">
        <xs:sequence>
            <xs:element name="make" type="xs:string"> 
            <xs:element name="model" type="xs:string"> 
            <xs:element name="colour" type="xs:string" minOccurs="0"/> 
            <xs:element name="engine-size" type="xs:string"> 
            <xs:element name="door-count" type="xs:string" minOccurs="0"/> 
        </xs:sequence>
    </xs:complexType>   

    <xs:element name="Car"  type="CarType" />

</xs:schema>

I want to add the element "colour" to the document. The sort of API I am looking for allow something like the following:

Element doorElement = document.createElement("door-count");
colourElement.setTextContent("4");
Element colourElement = document.createElement("colour");
colourElement.setTextContent("Black");

XMLHelper xmlHelper = new XMLHelper(document, schema);
xmlHelper.addChild(carNode, doorElement);
xmlHelper.addChild(carNode, colourElement);

The effect of this would be to throw an Exception if the child element is not a valid child of the parent element, or to insert it in the correct place in the parent node if it is a valid child:

<?xml version="1.0" encoding="utf-8"?>
<car>
    <make>Ford</make>
    <model>T</model>
    <colour>Black</colour>
    <engine-size>1600</engine-size>
    <door-count>4</door-count>
</car>

If anyone knows of an API that can acheive this, I would be grateful to know!