Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the values of an attribute of an element using XMlElement

I am working on XmlElement in c#. I have an XmlElement. The source of the XmlElement will look like the sample below.

Sample:

<data>
    <p>hello all
        <strong>
            <a id="ID1" href="#" name="ZZZ">Name</a>
        </strong>
    </p>
    <a id="ID2" href="#" name="ABC">Address</a>
</data>

I have to loop through the above XML to Search for element name a. I also want to extract the ID of that element into a variable.

Basically I want to get the ID attribute of the element <a>. It may occur as a child element or as a separate parent.

Can any one help how it can be done.

like image 744
Patan Avatar asked May 09 '12 11:05

Patan


1 Answers

Since you're using C# 4.0 you could use linq-to-xml like this:

XDocument xdoc = XDocument.Load(@"C:\Tmp\your-xml-file.xml");
foreach (var item in xdoc.Descendants("a"))
{
   Console.WriteLine(item.Attribute("id").Value);
}

Should give you the element a regardless of where it is in the hierarchy.


From your comment, for code that only uses the XmlDocument and XmlElement classes the equivalent code would be:

XmlDocument dd = new XmlDocument();
dd.Load(@"C:\Tmp\test.xml");
XmlElement theElem = ((XmlElement)dd.GetElementsByTagName("data")[0]);
//         ^^ this is your target element 
foreach (XmlElement item in theElem.GetElementsByTagName("a"))//get the <a>
{
    Console.WriteLine(item.Attributes["id"].Value);//get their attributes
}
like image 150
gideon Avatar answered Oct 07 '22 16:10

gideon