简体   繁体   中英

How to access element name using attribute value from Xml

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 (egin my example attribute class =" ایر") I want to get its corresponding element name (ie element= "year").

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=""' ایر'""]");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM