[xsd-users] Setting xsi:nil=true

Boris Kolpackov boris at codesynthesis.com
Thu Jun 28 04:22:22 EDT 2007


Hi Steinar,

Steinar Rune Eriksen <steinar at viz.no> writes:

> My initial problem was however how to actually create documents with
> this attribute.
>
> Example
>
> <MyMessage>
>    <ChildElement xsi:nil="true"/>
> </MyMessage>

I see. I think the easiest way is to use type customization and "override"
the serialization operator to set this attribute if the value is NULL.
The wildcard example in examples/cxx/tree/custom/wildcard/ shows how
to do that as well.

One way to wrap this all nicely is to make your custom type a "smart
pointer" for the original type, so that when xsi:nil is set to true,
the value of the pointer is 0, and when the value of the pointer is
0, the serialization operator sets xsi:nil.

Here is the outline of this approach. Let's say the type for ChildElement
is ChildType. As in the wildcard example we will generate the original
type, but will name it ChildTypeImpl (in the wildcard example it is
called date_base). So we will use this option:

--custom-type ChildType=/ChildTypeImpl

Then we provide implementation for ChildType which is a smart pointer
for ChildTypeImpl (pseudo-code):

class ChildType: xml_schema::type
{
public:
  ~ChildType ()
  {
    delete impl_;
  }

  // Parsing c-tor.
  //
  ChildType (const DOMElement& e)
    : impl_ (0)
  {
    if (!xsi_nil_set (e))
    {
      impl_ = new ChildTypeImpl (e);
    }
  }

  ChildTypeImpl*
  operator-> ()
  {
    return impl_;
  }

  ChildTypeImpl&
  operator* ()
  {
    return *impl_;
  }

  bool
  is_nil () const
  {
    return impl_ == 0;
  }

private:
 ChildTypeImpl* impl_;
};

// Serialization operator.
//
void operator<< (DOMElement& e, const ChildType& x)
{
  if (x.is_nil ())
  {
    // set xsi:nil
  }
  else
  {
    s << *x;
  }
}


> If I wanted to specify a NULL value instead for ChildElement, this is
> where my problems are.  Is there anyway to get access to the xerces
> Dom model during construction of the tree? Then I could manually add
> the xsi:nil part.

Yes, that would be the serialization operator.


> I have tried the following:
>
> MyMessage::ChildElement::type  childElement;
>
> xercesc::DOMNode* n = childElement._node();
>
> // FAILS here since n is NULL when returned from _node()

Right, _node() returns a DOM node that was associated with this tree
node during parsing. Since you are constructing the tree from scratch,
there is no DOM association.

hth,
-boris




More information about the xsd-users mailing list