0

Parent xsd :

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="SpecialOption">
        <xs:complexType>
            <xs:simpleContent>
                <xs:extension base="xs:string">
                    <xs:attribute name="Option" type="xs:string"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>
    </xs:element>
</xs:schema>

After modifying xsd: Adding use="required" field

<xs:element name="SpecialOption">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute name="Option" type="xs:string" use="required"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

I want to add the use="required" field to the parent xsd and generate a new xsd file. I want to do this programmatically from a java code.

currently, I am following the below method to read the xsd file but cannot figure out a way to add the use="required" attribute How to Programmatically Update and Add Elements to an XSD

Any help here is very much appreciated.Thank you

1 Answers1

2

Use XSLT. Assuming XSLT 3.0:

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="xs:element[@name='SpecialOption']//xs:attribute[@name='Option']">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:attribute name="use">required</xsl:attribute>
  </xsl:copy>
</xsl:template>
</xsl:transform>

It's not difficult with earlier versions of XSLT, just a bit more verbose.

(You asked for Java, but of course you can easily run an XSLT transformation from Java, and this is much easier than hand-coding it with low-level DOM manipulation).

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • The parent xsd is obtained from a supplier, I want to keep the same format with only use="required" field added and generate a new .xsd file. And, I wanted to modify the parent xsd file in java. What I am looking for is that the generated xsd file will be exactly same as the parent xsd but only the required attribue should be made mandatory. – AdarshVShetty Apr 02 '20 at 09:36
  • Yes, I thought that's what you wanted and that's what my solution does. – Michael Kay Apr 02 '20 at 12:11
  • Good answer, +1 from my side! – Yitzhak Khabinsky Apr 02 '20 at 12:39
  • @MichaelKay Thank you for the answer. I applied the transform provided by you via java code.The required field is added but the parent tags are removed.This is how the transformed xsd looks now. ** ** – AdarshVShetty Apr 03 '20 at 05:26
  • Added this code before the code @MichaelKay provided, works fine – AdarshVShetty Apr 03 '20 at 08:30
  • I did say you would need extra code if you wanted to use an earlier version of XSLT pre-3.0... – Michael Kay Apr 03 '20 at 09:17