How to access element name using attribute value from Xml

115 views Asked by At

I have an XML file with code:

<?xml version="1.0" encoding="utf-8"?>
<car_ads>
<car_make make="suzuki" adj_kw="null">
<model data_type="string"adj_kw="null" class="کار_ماڈل ">
   <model_instance>ALTO</model_instance>
   <model_instance>KHYBER</model_instance>
</model>
<year data_type="integer" adj_kw="yes" class="ایر ">
   <adj_kw>ماڈل </adj_kw>
   <adj_kw>ء</adj_kw>
</year>
<price data_type="string" adj_kw="yes" class=" قیمت  " >
    <adj_kw>قیمت  </adj_kw>
    <adj_kw>ڈیمانڈ </adj_kw>
</price>
</car_make>
<car_make make="سوزوکی" adj_kw="null">
<model data_type="string" adj_kw="null" class="کار_ماڈل ">
    <model_instance>alto</model_instance>
    <model_instance>آلٹو</model_instance>
</model>
<year data_type="integer" adj_kw="yes" class="ایر ">
    <adj_kw>ماڈل </adj_kw>
    <adj_kw>ء</adj_kw>
    <adj_kw>ایئرآفمینوفیکچرنگ </adj_kw>
</year>
<price data_type="string" adj_kw="yes" class=" قیمت  " >
    <adj_kw>قیمت  </adj_kw>
    <adj_kw>ڈیمانڈ </adj_kw>
</price>
</car_make>
</car_ads>

I am parsing this using XmlDocument in c#

string xmlText = File.ReadAllText(@"G:\\car_xml_final.xml");
var doc = new XmlDocument();
doc.LoadXml(xmlText);

If I know attribute value (e.g.in my example attribute class =" ایر") I want to get its corresponding element name (i.e element= "year").

2

There are 2 answers

5
Glorfindel On

Thanks @Charles Mager for pointing out the difference between XmlDocument and XDocument. If you use XDocument, you can use either LINQ:

var element = doc.Root.Descendants().FirstOrDefault(e => e.Attribute("class") == " ایر");
var elementName = element.Name;

or XPath:

var element = doc.XPathSelectElement("//[@class=' ایر']");
var elementName = element.Name;

to get your desired result.

If you stick to XmlDocument, there's the SelectSingleNode method:

var element = doc.DocumentElement.SelectSingleNode("descendant::[class=""' ایر'""]");
0
har07 On

As mentioned in the other answer, you can use SelectSingleNode() or SelectNodes() to get sepcific element(s) from XmlDocument passing an XPath expression as parameter, for example :

var result = doc.SelectNodes("//*[@class='ایر ']");
foreach (XmlNode node in result)
{
    //print element name
    Console.WriteLine(node.Name);
}

brief explanation about XPath being used :

  • //* : select all elements regardless of the name (*), anywhere in the XML document (//)...
  • [@class='some_class_here'] : ...having class attribute value equals certain class name