Wednesday 11 December 2013

C# Tips : Check XML element has attribute using LINQ with C#.Net and VB.Net example

Using LINQ you can check that attribute exist in element or not. There is property called "HasAttributes" of XElement class to check existence of attribute.

Here is example for this.

In this example we take one 'customers.xml' file which contains customers information like name, id, etc. Now we check that does "customer" element has 'id' attribute or not. In XML there is one customer 'David' which does not have 'id' attribute. Now we iterate each 'customer' element and display that it element has attribute or not.


C#. Net Example :
        XDocument doc = XDocument.Load((Server.MapPath("customer.xml")));
        foreach (var objElement in doc.Descendants("customer"))
        {
            Response.Write("<b>Customer Name : </b>" + objElement.Element("name").Value);
            Response.Write("<br/>");
            Response.Write("<b>Customer has attributes? </b>" + objElement.HasAttributes.ToString());
            Response.Write("<br/>");
            Response.Write("<br/>");
        }

VB.Net Examples :
        Dim doc As XDocument = XDocument.Load((Server.MapPath("customer.xml")))
        For Each objElement As XElement In doc.Descendants("customer")
            Response.Write("<b>Customer Name : </b>" + objElement.Element("name").Value)
            Response.Write("<br/>")
            Response.Write("<b>Customer has attributes? </b>" & objElement.HasAttributes.ToString())
            Response.Write("<br/>")
            Response.Write("<br/>")
        Next

customer.xml File :
<?xml version="1.0" encoding="utf-8" ?>
<customers>
    <customer id="1">
        <name>Rahul</name>
    </customer>
    <customer id="2">
        <name>Sachin</name>
    </customer>
    <customer>
        <name>David</name>
    </customer>
</customers>

Output : 
Check XML Element has attribute


Below are the books that you would like :

1 comment: