Search code examples
xmlxsddtdietf-netmod-yang

How to define constants in YANG?


I am trying to write a YANG file to capture an XML schema. I want to model an XML like the following.

`<stream>
     <filter>
         <type>inbuilt</type>
         <attribute>a1</attribute>
         <attribute>a2</attribute>
     </filter>
     <variables>anything</variables>
 </stream>
`

I want the 'filter' element and its children to be present along with their values in all the XMLs generated. And the values should be constants. Is it possible with the current YANG modeling? I tried understanding the YANG specification, but I could never find a keyword for constants.


Solution

  • If I understand correctly, the values in your XML snippet are never expected to change? The following would make your XML snippet the only valid instance (if we ignore the fact that variables can be anything):

    container stream {
      container filter {
        leaf type {
          type enumeration {
            enum "inbuilt";
          }
          mandatory true;
        }
        leaf-list attribute {
          type enumeration {
            enum "a1";
            enum "a2";
          }
          min-elements 2;
        }
      }
      leaf variables {
        type string;
      }
    }
    

    The enumeration data type may be used for requiring constant string values. In my example inbuilt will be the only valid value for type leaf. The mandatory and min-elements statements are there to constrain the instance and force it to always contain type and the two attribute instances.

    If you need to reuse this pattern, put it in a grouping statement and reference it with a uses statement.