Search code examples
c#xmlxelement

In a Xml how to iterate within node which is having similar property in c#


I have a xml as below: In this i have to find value of Generic Field "FetchItems"

<ExtendedProperties>
        <GenericField>
          <FieldKey>creatorSalesRepId</FieldKey>
          <FieldValue>12345</FieldValue>
          <ExtendedProperties />
        </GenericField>
        <GenericField>
          <FieldKey>creatorSalesRepBadgeId</FieldKey>
          <FieldValue>1123456</FieldValue>
          <ExtendedProperties />
        </GenericField>
        <GenericField>
          <FieldKey>defaultShipmentId</FieldKey>
          <FieldValue>m2T9yuwJSEi_XNAE7m</FieldValue>
          <ExtendedProperties />
        </GenericField>
        **<GenericField>
          <FieldKey> FetchItems</FieldKey>
          <FieldValue>
 {"Items": [
        {
            "ItemId": "c1d2669e-032d-41fd-90c5-fa6a850f2070",
            "CategoryViews": [
                {
                    "CategoryId": "",
                    "Prices": null}]}]}
          </FieldValue>
          <ExtendedProperties />
   <ExtendedProperties>   

so far i have tried : objTo is having input xml

public ExtendedProperty(XElement objExtTo)
           {
               if (objExtTo == null) return;
                   if (Element("ExtendedProperties") != null)
                       ItemView = Element("ExtendedProperties").Value;

            }

Any suggestion how to iterate through Generic Field Where Key == "FetchItems"


Solution

  • You can try using XDocument and LINQ

    var xDoc = XDocument.Parse(File.ReadAllText("XMLFile4.xml"));
    var result = xDoc.Descendants("GenericField")
                     .Where(x => x.Element("FieldKey").Value == "FetchItems")
                     .Select(x => x.Element("FieldValue").Value);