1

I need to do duplicate check with in xml element attribute value.

Sample Input Request:

 <Parent>
   <child id="1"> test 1</child>
   <child id="1"> test 2</child>
   <child id="2"> test 3</child>
</parent>

I want to find duplicate id which is present in child element attribute in the request xml using XSD or some other way would be fine.Anyone please help me to detect duplicate element attribute value.

1

1 Answer 1

1

Basically you need to use xsd:unique for enforcing uniqueness for an element or attribute. Below is the excerpt from the link:

Specifies that an attribute or element value (or a combination of attribute or element values) must be unique within the specified scope. The value must be unique or nil.

In case if you are not aware then you need to create an XSD/DTD using which you can enforce this uniqueness and then validate your XML against that XSD/DTD using any of the available XML parser. Below is a Java example along with the XSD.

Your statement in question:

request xml using XSD or some other way would be fine

As per best of my knowledge if you want to check your XML document for its validity then you MUST have either an XSD or DTD, there is no other way you can do it without having an XSD or DTD (or lesser known RELAX NG). So, all you need to do is write a XSD or DTD which defines the expected structure of your XML document, and then using some XML validator to validate your XML document against that XSD/DTD and it will tell you whether your XML document adheres to the XSD/DTD or not. Bottom line is that you need to write/specify a XSD/DTD which defines the expected structure of your XML document.

Your XML: "so.xml"

<Parent>
   <child id="1"> test 1</child>
   <child id="2"> test 2</child>
   <child id="2"> test 3</child>
</Parent>

Sample XSD you need (with xsd:unique for your requirement): "so.xsd"

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Parent">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:simpleContent>
                            <xs:extension base="xs:string">
                                <xs:attribute name="id" type="xs:token" use="required"/>
                            </xs:extension>
                        </xs:simpleContent>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    <!-- This is the solution of your problem - "xs:unique" -->   
    <xs:unique name="unique-id">
          <xs:selector xpath="child"/>
          <xs:field xpath="@id"/>
       </xs:unique>
    </xs:element>
</xs:schema>

Sample Java code for validation:

import org.w3c.dom.Document; 
import org.xml.sax.SAXException; 
import org.xml.sax.SAXParseException; 
import org.xml.sax.InputSource; 


import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringReader; 


import javax.xml.XMLConstants; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.parsers.ParserConfigurationException; 
import javax.xml.transform.Source; 

import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamSource; 
import javax.xml.validation.Schema; 
import javax.xml.validation.SchemaFactory; 
import javax.xml.validation.Validator; 

public class XmlSchemaValidationHelper { 

    public static void main(String[] argv) {
        XmlSchemaValidationHelper schemaValidationHelper = new XmlSchemaValidationHelper();
        schemaValidationHelper.validateAgainstSchema(new File(argv[0]), new File(argv[1]));
    }

    public void validateAgainstSchema(File xmlFile, File xsdFile) { 
        try {
            System.out.println("### Starting...");
            // parse an XML document into a DOM tree 
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
            builderFactory.setNamespaceAware(true); 
            DocumentBuilder parser = builderFactory.newDocumentBuilder(); 
            Document document = parser.parse(xmlFile); 

            // create a SchemaFactory capable of understanding WXS schemas 
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

            // load a WXS schema, represented by a Schema instance 
            Source schemaFile = new StreamSource(xsdFile); 
            Schema schema = factory.newSchema(schemaFile); 

            // create a Validator instance, which can be used to validate an 
            // instance document 
            Validator validator = schema.newValidator(); 

            // validate the DOM tree 
            validator.validate(new DOMSource(document));
            System.out.println("### Finished...");

        } catch (FileNotFoundException ex) { 
            throw new OpenClinicaSystemException("File was not found", ex.getCause()); 
        } catch (IOException ioe) { 
            throw new OpenClinicaSystemException("IO Exception", ioe.getCause()); 
        } catch (SAXParseException spe) { 
            spe.printStackTrace(); 
            throw new OpenClinicaSystemException("Line : " + spe.getLineNumber() + " - " + spe.getMessage(), spe.getCause()); 
        } catch (SAXException e) { 
            throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); 
        } catch (ParserConfigurationException pce) { 
            throw new OpenClinicaSystemException(pce.getMessage(), pce.getCause()); 
        } 
    } 

    public class OpenClinicaSystemException extends RuntimeException { 
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String errorCode; 
        private Object[] errorParams; 

        public OpenClinicaSystemException(String code, String message) { 
            this(message); 
            this.errorCode = code; 
        } 

        public OpenClinicaSystemException(String code, String message, Throwable cause) { 
            this(message, cause); 
            this.errorCode = code; 
        } 

        public OpenClinicaSystemException(String message, Throwable cause) { 
            super(message, cause); 
        } 

        public OpenClinicaSystemException(Throwable cause) { 
            super(cause); 
        } 

        public OpenClinicaSystemException(String message) { 
            super(message); 
            this.errorCode = message; 
        } 

        public OpenClinicaSystemException(String code, Object[] errorParams) { 
            this.errorCode = code; 
            this.errorParams = errorParams; 
        } 

        public OpenClinicaSystemException(String code, Object[] errorParams, String message) { 
            this(message); 
            this.errorCode = code; 
            this.errorParams = errorParams; 
        } 

        public String getErrorCode() { 
            return errorCode; 
        } 

        public Object[] getErrorParams() { 
            return errorParams; 
        } 

        public void setErrorParams(Object[] errorParams) { 
            this.errorParams = errorParams; 
        } 
    }

}

You can run this program as - java XmlSchemaValidationHelper so.xml so.xsd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.