Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C# XML validation without schema

Posted on 2009-06-29
13
Medium Priority
?
1,225 Views
Last Modified: 2013-12-17
Hello everybody

I'm looking for some easy way to check all the Tags in an XML file. To see if they are properly closed and so on. So check the whole structure of the XML file without a schema.

Could somebody give me an example how to do this? I'm a noob ;)

0
Comment
Question by:socom1985
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
13 Comments
 
LVL 11

Expert Comment

by:saragani
ID: 24736191
You can do it by:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(string XmlFileContent);


or by:
xmlDoc.Load(string filename)

The load / LoadXML would throw an exception if the XML is not OK (Missing tags, invalid chars etc)
0
 
LVL 19

Expert Comment

by:daveamour
ID: 24736377
saragani is right - here is some code implementig that idea.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ValidateXML
{
    class Program
    {
        static void Main(string[] args)
        {
            //Valie
            string test1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person></People>";
 
            //Invalid
            string test2 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person>";
 
            Console.WriteLine(IsValidXML(test1));
            Console.WriteLine(IsValidXML(test2));
 
            Console.Read();
        }
 
        static bool IsValidXML(string xmlContent)
        {
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 
                doc.LoadXml(xmlContent);
            }
            catch
            {
                return false;
            }
 
            return true;
        }
    }
}

Open in new window

0
 
LVL 1

Author Comment

by:socom1985
ID: 24742852
Thanks this helps.. But can you also tell me how to get the error? I want to see the location in the file..
0
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!

 
LVL 19

Expert Comment

by:daveamour
ID: 24742884
If you want to see an error just try the attahced

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ValidateXML
{
    class Program
    {
        static void Main(string[] args)
        {
            //Valie
            string test1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person></People>";
 
            //Invalid
            string test2 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person>";
 
            Console.WriteLine(IsValidXML(test1));
            Console.WriteLine(IsValidXML(test2));
 
            Console.Read();
        }
 
        static bool IsValidXML(string xmlContent)
        {
            //try
            //{
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 
                doc.LoadXml(xmlContent);
            //}
            //catch
            //{
                //return false;
            //}
 
            return true;
        }
    }
}

Open in new window

0
 
LVL 1

Author Comment

by:socom1985
ID: 24743085
I want to write the exeption into a string. I'm writing a tool that checks every XML File in a directory and shows all errors at the end.

I now see another problem with this method. I think it will only show me the first error in an xml. Its not a big problem but it would be great if you had another method for this problem.
0
 
LVL 19

Expert Comment

by:daveamour
ID: 24743127
Ok I see - well we could fix the current code sample to give you the error message as a string easily enough but yes it will only give you the first error.
I don't know of any easy way of finding all errors programmatically I'm afraid.  There should be somethng somewhere you can reuse.  If not you would have to write something yourself but that would be very difficult and tedious.
0
 
LVL 1

Author Comment

by:socom1985
ID: 24752071
Hmm I see.. Ok. Then we should go with the current code sample and just the first error. Can I do a catch (Exception e) or what would you suggest?

Thanks..
0
 
LVL 1

Author Comment

by:socom1985
ID: 24752095
If i do it with Exception e and e.Message I just get "Root element is missing." but I cant see which element..
0
 
LVL 19

Accepted Solution

by:
daveamour earned 2000 total points
ID: 24752107
Its a matter of coding style really but I might do it something like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ValidateXML
{
    class Program
    {
        static void Main(string[] args)
        {
            //Valie
            string test1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person></People>";
 
            //Invalid
            string test2 = "<?xml version=\"1.0\" encoding=\"utf-8\"?><People><Person><Name>Dave</Name></Person>";
 
            Validator validator = new Validator();
 
            if (validator.ValidateXml(test1))
            {
                Console.WriteLine("Test1 is valid" + Environment.NewLine);
            }
            else
            {
                Console.WriteLine("Test1 is not valid: " + validator.ValidationErrorMessage + Environment.NewLine);
            }
 
            if (validator.ValidateXml(test2))
            {
                Console.WriteLine("Test2 is valid" + Environment.NewLine);
            }
            else
            {
                Console.WriteLine("Test2 is not valid: " + validator.ValidationErrorMessage + Environment.NewLine);
            }           
 
            Console.Read();
        }
    }
 
    class Validator
    {
        public string ValidationErrorMessage
        {
            get;
            set;
        }
        
        public bool ValidateXml(string xmlContent)
        {
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 
                doc.LoadXml(xmlContent);
            }
            catch (Exception ex)
            {
                ValidationErrorMessage = ex.Message;
 
                return false;
            }
 
            return true;
        }
    }
}

Open in new window

0
 
LVL 19

Expert Comment

by:daveamour
ID: 24752110
Its the Root element
0
 
LVL 1

Author Comment

by:socom1985
ID: 24752119
Thanks for the code..
I changed a random closing tag. not the root element..
0
 
LVL 19

Expert Comment

by:daveamour
ID: 24752131
Sorry but the messages given by the parsing engine used by System.Xml.XmlDocument is out of my control I'm afraid!
0
 
LVL 1

Author Closing Comment

by:socom1985
ID: 31597880
Thanks. That's exactly it..
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

688 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