Share via

Ignore Empty XML Data

Yusuf 791 Reputation points
2021-03-28T09:19:58.197+00:00

Hi
I have an XML API service and this is an example. It displays four XML forms, one of the forms does not contain data in Note node and Item node.
[Open link][1] and refresh the page to notice the difference

How can I ignore the empty XML data so the only XML that contain data will be display?

Code

using System;
using System.Xml;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("https://test.test.com/");
            XmlNode noteNode = doc.DocumentElement.SelectSingleNode("/ROOT/Note");
            XmlNode itemsNode = doc.DocumentElement.SelectSingleNode("/ROOT/Items");
            Console.WriteLine(noteNode.Attributes["Title"].InnerText);
            foreach (XmlNode node in itemsNode.ChildNodes)
            {
                Console.WriteLine("\t" + node.InnerText);
            }
        }
    }
}
Thank you in advance  
  
  
   
  
  
  
  
  
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-03-28T09:36:28.823+00:00

Try something like this:

var items = doc.SelectNodes( "/ROOT/Items/Item[text()|*|@*]" );

foreach( XmlNode item in items )
{
   . . .
}

It returns <Item> nodes that have text, child nodes or attributes. You can adjust the condition for your needs.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.