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").
Thanks @Charles Mager for pointing out the difference between
XmlDocument
andXDocument
. If you useXDocument
, you can use either LINQ:or XPath:
to get your desired result.
If you stick to
XmlDocument
, there's theSelectSingleNode
method: