Vijay
Vijay

Reputation: 3502

How to search the XML tag?

I want to search the tags in XML. My XML is:-

<school>
  <student>
    <firstname>Vijay</firstname>
    <lastname>Prabhu</lastname>
    <age>27</age>
    <photo>/NewExample;component/Images/icon_man.png</photo>
  </student>
  <student>
    <firstname>Arun</firstname>
    <lastname>Prasath</lastname>
    <age>5</age>
    <photo>/NewExample;component/Images/icon_man.png</photo>
  </student>
  <student>
    <firstname>Satheesh</firstname>
    <lastname>Kumar</lastname>
    <age>27</age>
  </student> 
</school>

Here I want to check <photo> tag is available or not. I have try like this.

  var school= from ack in xdoc.Descendants("school")
                           select ack;
for(int i =0;i<school.count();i++)
{
  if(school.ElementAt(i).Element("photo").Name.LocalName.Equals("photo"));
    Console.WriteLine("Tag is available in==>"+i);
  else
    Console.WriteLine("Tag is Not available in==>"+i);
}

It is working. But when I use this same in another example with diff elements it showing error. Please let me know any other effective way to search the Tags in c#.

Thanks in advance.

Upvotes: 1

Views: 184

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Get all students. Then try to retrieve photo element from student element. If it is equal to null then photo no exist in current student:

var students = xdoc.Root.Elements("student");
int i = 1;
string format = "Tag is {0}available in {1}";

foreach(var student in students)
   Console.WriteLine(format, student.Element("photo") == null ? "not " : "",i++);

Output:

Tag is available in 1
Tag is available in 2
Tag is not available in 3

You can write extension to make code more readable

public static bool HasElement(this XElement parent, XName name)
{
    return parent.Element(name) != null;
}

E.g. selecting all students which have photo will look like

from student in xdoc.Root.Elements("student")
where student.HasElement("photo")
select student

You also can use XPath for same task

xdoc.XPathSelectElements("school/student[photo]")

Upvotes: 2

Related Questions