How to get element attribute values ​​using XMlElement

I am working on an XmlElement in C #. I have an XmlElement . The XmlElement source will look like this.

Example:

 <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 need to go through the above XML to find the name of the element a . I also want to extract the identifier of this element into a variable.

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

Can anyone help how this can be done.

+6
source share
1 answer

Since you are using C # 4.0, you can use linq-to-xml as follows:

 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 no matter where it is in the hierarchy.


From your comment, for code that uses only 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 } 
+4
source

Source: https://habr.com/ru/post/915278/


All Articles