Please disable your adblock and script blockers to view this page
 

How to check XML string valid and well formed or not in Asp.Net C#, VB

Introduction: In this article I am going to explain How to validate XML String in Asp.Net using both C# and VB.


Implementation: Let’s create a sample page for demonstration purpose.

Asp.Net C# Code to validate XML string

 protected void Page_Load(object sender, EventArgs e)
    {
        string xmlStr = "<ROOT><Employee Id='100'/><Employee Id='134'/><Employee Id='178'/></ROOT>";
        if (IsValidXML(xmlStr))
        {
            Response.Write("XML is well formed");
        }
        else
        {
            Response.Write("XML is not well formed");
        }
    }

    private bool IsValidXML(string xmlStr)
    {
        try
        {
            if (!string.IsNullOrEmpty(xmlStr))
            {
               System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.LoadXml(xmlStr);              
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (System.Xml.XmlException)
        {
            return false;
        }
    }

Asp.Net VB Code to validate XML string

   Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 
        Dim xmlStr As String = "<ROOT><Employee Id='100'/><Employee Id='134'/><Employee Id='178'/></ROOT>"
        If IsValidXML(xmlStr) Then
            Response.Write("XML is well formed")
        Else
            Response.Write("XML is not well formed")
        End If
   End Sub

    Private Function IsValidXML(xmlStr As String) As Boolean
        Try
            If Not String.IsNullOrEmpty(xmlStr) Then
                Dim xmlDoc As New System.Xml.XmlDocument()
                xmlDoc.LoadXml(xmlStr)
                Return True
            Else
                Return False
            End If
        Catch generatedExceptionName As System.Xml.XmlException
            Return False
        End Try
    End Function

 Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon