question

yusuf2 avatar image
0 Votes"
yusuf2 asked cheong00 edited

Ignore Empty XML Data

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 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.darwishshelves.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






dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered cheong00 edited

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.

· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you for the reply.
I tested the code.
https://dotnetfiddle.net/Vs8XRr
I'm looking for a way to ignore data when both Note and Item are empty


0 Votes 0 ·

Then include the title into your tests, for example:

 string title = doc.SelectSingleNode( "/ROOT/Note/@Title" ).Value;
 var items = doc.SelectNodes( "/ROOT/Items/Item[text()|*|@*]" );
    
 if( string.IsNullOrWhiteSpace( title ) && items.Count == 0 )
 {
     Console.WriteLine( "The document is empty" );
 }
 else
 {
     Console.WriteLine( "Title: {0}", title );
     Console.WriteLine( "Items:" );
     foreach( XmlNode item in items )
     {
         Console.WriteLine( "\t" + item.InnerText );
     }
 }
1 Vote 1 ·

Thank you for the answer.
That's a great way.
But how can I ignore empty data to go to next result? e.g. using while loop?

0 Votes 0 ·
Show more comments

@yusuf2 : Unless the reply contains your personal data or other things that is decided to be inappropriate in this forum, request to delete posts made by other members will not be entertained.

I'll just help you edit away the URL in code.

0 Votes 0 ·