Search code examples
c#xmlxsdxelement

Hiding XElement nodes with no data


I am having trouble hiding XElements with no data.

If I have this code:

string missing = string.Empty;
XElement missingNodes = new XElement("TOPLEVEL",
    new XElement("FIELD1", "VALUE1"),
    new XElement("FIELD2", missing),
    new XElement("FIELD3", "VALUE3")
);

I end up building this schema:

<TOPLEVEL>
  <FIELD1>VALUE1</FIELD1>
  <FIELD2></FIELD2>
  <FIELD3>VALUE3</FIELD3>
</TOPLEVEL>

If I change missing to have null instead of String.Empty, the second field becomes:

<FIELD2 />

Is there an easy way to hide the nodes with empty/null data?

I'd like it to look more like this:

<TOPLEVEL>
  <FIELD1>VALUE1</FIELD1>
  <FIELD3>VALUE3</FIELD3>
</TOPLEVEL>

EDIT:

Following the advice of @sine and @gunr2171, I went down the path of not adding the empty/null nodes.

Since I wanted to keep everything in the nested new format (without a lot of if/then branches) I tried using a triconditional check for null. Interestingly XElement leaves no artifacts if you pass a null as the contents of anything.

So this did the trick:

string missing = null;
XElement missingNodes = new XElement("TOPLEVEL",
    new XElement("FIELD1", "VALUE1"),
    (missing != null ) ? new XElement("FIELD2", missing) : null,
    new XElement("FIELD3", "VALUE3")
);

Solution

  • I believe @sine is right. You just need to check if the value is null/empty and not insert the value.

    public void AddIfValid(XElement root, string tagName, string value, string excludeValue)
    {
        if (value != excludeValue)
            root.Add(new XElement(tagName, value);
    }