[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Reject an Invalid XML File

Posted on 2006-04-04
3
Medium Priority
?
183 Views
Last Modified: 2013-11-19
Hello:

I have the following code, that can read an xml file and display on a console application.

Now, I have tried adding code, that can be called if the xml isnt in the right format..

But for some weird reason, its not working.
Can anyone please take a look at the following code, and let me know what to do, incase the xml file isnt in the right format and should be able to display the message: "Failed to Load File"

THanks.


using System;
using System.IO;
using System.Xml;

namespace TestUtility
{
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      class EntryPoint
      {
            private bool m_bIsFailure= true ;
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
                  //checking to see if length of aruguments is less than 1,
                  //therefore displaying  no parameters have been entered
                  if( args.Length < 1 )
                  {
                        Console.WriteLine("No Parameters Have Been Entered");
                        Console.ReadLine();
                  }
                  // this checks to see that # of arguments passed in are 2 ,
                  // This executes the xml content as the # of arguments that we have passed are 2.
                  if( args.Length >0 && args.Length < 3)
                  {
                        if(args.GetValue(0).ToString()== "/xml")
                        {
                              Execute_Cmd_xml(args);
                        }
                        else
                        {
                              Console.WriteLine("Unrecognised command");
                              Console.ReadLine();
                        }
                  }
                  else
                  {
                        //In case the input parameter doesnt have a double quotes, alert to specify that quotes are needed
                        Console.WriteLine("The path must contain double quotes around it");
                        Console.ReadLine();
                        Console.WriteLine("The xml isnt properly formatted"); // new code 4/4/2006 - should be deleted if problems
                  }
            }

            //new code for in proper xml format

            private void ValidationFailed (object sender,ValidationEventArgs args)
            {
                  m_bIsFailure = true;
                  Console.WriteLine("Invalid XML File: " + args.Message);
            }


            //end of in proper xml format
            static void Execute_Cmd_xml(string[] args)
            {
                  string sIFolderName =""; // declare an empty string
                  // If the # of args passed is only 1 instead of 2, alert for a path to be provided.
                  if (args.Length==1)
                  {
                        Console.WriteLine("Please Provide a Path");
                        Console.ReadLine();
                  }
                  try
                  {
                        XmlDocument doc = new XmlDocument();   // create an object
                        sIFolderName=args[1];                  // assigning second argument to the declared variable.
                        //if file exists, load the document,
                        //start selecting each node, and
                        //start with first key or value of 2nd key of each node.
                        if (System.IO.File.Exists(sIFolderName))
                        {
                              doc.Load(sIFolderName);
                              //This is to display the keys and values of the xml file.
                              //Get each key and the corresponding values
                              //using a variable xn
                              foreach (XmlNode xn in doc.SelectNodes("elite_dms/app_settings/add"))
                              {
                                    Console.WriteLine("Key = {0} Value = {1}",xn.Attributes.GetNamedItem("key").Value,xn.Attributes.GetNamedItem("value").Value );
                              }
                              Console.ReadLine();
                        }
                        else
                        {
                              Console.WriteLine("Failed to Load Xml Document: {0}",sIFolderName);
                              Console.ReadLine();
                        }
                  }
                  catch(XmlException xmlEx)
                  {
                        Console.WriteLine(xmlEx.Message);
                        Console.ReadLine();
                  }
            }
      }
}



0
Comment
Question by:Reetu2005
1 Comment
 
LVL 21

Accepted Solution

by:
MogalManic earned 200 total points
ID: 16379609
Does your XML have a schema?

If so, then the XmlDocument class is not validating from the schema.  To validate, just load a slightly different way:
    XmlDocument doc = new XmlDocument();

    //Load the XML using the
    XmlValidatingReader = new XmlValidatingReader(new XmlTextReader(sIFolderName));

    doc.Load(reader);

This wil throw an exception if the XML does not match the schema associated with the XML filename

If you don't want to be that strict and/or you don't have a schema, then you can just put a count of the node list returned by
  doc.SelectNodes("elite_dms/app_settings/add")
if the count of the nodelist is 0, then throw an exception saying:"There are no 'elite_dms/app_settings/add' node"
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Progress

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question