1

How to Validate XmlNodes in Xml Document?

We have to clear about terms “XMLNodes” and “XMLDocument”.

XMLDocument : very simple way any file with extension .xml is a “XMLDocument”.

And Every XMlDoc has an one or more XMLNodes.

Let me Explain in Brief….

Let’s Guess here a XMlDocument Test.xml

<Test>   //Test is known as a XMlNode.
     <Test1>  // Test1 known as  a childnode of XMlnode Test.
            ID=”1″,     // Id and name known as Xml Attribute of Test1 node.
            Name=”Test”
    </Test1>
    <Test1>
            ID=”2″,
            Name=”Test1″
    </Test1>
</Test>
Now you are understand basic concept of XMlNodes and XmlDoc.

Now fetch the Xml file from user or from source to validate the XMlnodes,

     You have to import Using Microsoft.XML;  // Namespace

var Doc = new XmlDocument();  // Variable to store the XmlDocument.
Doc.Load(“//Test.xml”); // To load our Xml file to Console application.
XmlNodeList AllfieldTags = Doc.GetElementsByTagName(“Test”);//Get all the child Nodes of the Test Node.
foreach(XmlNode CurrentFields in AllFieldTag)
       {
              this.Validate(CurrentFields);
        }
Public static class Validate(XmlNode Current)
{
     XmlNodelist list= Current.ChildNodes;
    for (int Index = 0; Index < list.Count; Index++)
{
for (int SubIndex = Index + 1; SubIndex < list.Count – 1; SubIndex++)
{
if ((list[Index].Attributes[“ID”].Value ==                     list[SubIndex].Attributes[“ID”].Value) ||       (list[Index].Attributes[“Name”].Value ==     list[SubIndex].Attributes[“Name”].Value))
{
flag = true;
break;
}
}
if (flag == true)
{
break;
}
}
if (flag == true)
{
return false;
}
else
{
return true;
}
}

U can Validate attribute value in XMl File Using For loop as i mention above code.

:):)!!Happy Coding!!:):)

Advertisements