Search code examples
c#xmldesign-decisions

Is having a scalar type and element inside a parent element bad design in XML?


We currently have the following structure as part of an API endpoint response.

<elements>
  <element arg1="" arg2="">id</element>
</element>

Now, I would like to add a sub-element to the element without changing the existing structure. This is what I had when adding the sub-element.

<elements>
  <element arg1="" arg2="">id
    <subelement arg1="" arg2="" />
  </element>
</element>

It seems like the easiest solution and as far as I read it's valid XML. But is it bad design? Would the API users be able to handle this well in their languages (mostly C#)?


Solution

  • Your candidate design uses mixed-content for data-oriented XML. You're right to suspect that it's non-ideal. Users will not be able to leverage the benefits of markup to access id separately from subelement; parsing and XPath access would be harder than necessary. If you're determined to use XML for data-oriented content, it would be better to have id wrapped in its own tag (or to use attributes for scalars -- see XML Element vs XML Attribute).

    More broadly, realize that using XML for data-oriented content has been out-of-favor for good reasons for more than a decade. New data-oriented APIs should not be based on XML. JSON is a commonly preferred alternative.

    XML in general and mixed-content in particular are best used for document-oriented data.

    See also