Thursday 12 April 2018

Workling With XElement And Read Data from XmlNode and Attributes

// C# Code to Create XElement

        XElement xBooks = new XElement("Books");
        XElement xBook = new XElement("Book",
        new XAttribute("Genere", "NV"),
        new XAttribute("Amount", "100")
        );
        xBooks.Add(xBook);
        XElement xPoductDetails = new XElement("PoductDetails");
        XElement xItem = new XElement("Item",
        new XAttribute("Name", "ABC"),
        new XAttribute("Fee", "100"),
        new XAttribute("ChargeFee", "100")
        );
        xPoductDetails.Add(xItem);
        xBooks.Add(xPoductDetails);
        XElement xDetail = null;
        xDetail = new XElement("Data",
            new XElement("ID", "12123"));
        xBooks.Add(xDetail);
        XElement xOrderDetails = new XElement("OrderDetails",
           new XAttribute("OrderId", "222"),
           new XAttribute("OrderDate", "2018-14-08")
           );

        xBooks.Add(xOrderDetails);

        // Below XElement Output Will get
        /*
         <Books>
          <Book Genere="NV" Amount="100" />
          <PoductDetails>
            <Item Name="ABC" Fee="100" ChargeFee="100" />
          </PoductDetails>
          <Data>
            <ID>12123</ID>
          </Data>
          <OrderDetails OrderId="222" OrderDate="2018-14-08" />
        </Books>
     
         */

        // Read Node and Attribute Values
        XElement xDoc = xBooks;
        string ID = xDoc.XPathSelectElement("Data/ID").Value;
        string OrderId = xDoc.XPathSelectElement("OrderDetails").Attribute("OrderId").Value;
        if (xDoc.XPathSelectElements("Book[@Genere='NV' or @Genere='EPIC']").Count() > 0)
        {
            foreach (XElement xNode in xDoc.XPathSelectElements("Book"))
            {
                string str1 = xNode.Attribute("Genere").Value;
            }
        }
        foreach (XElement xNode in xDoc.XPathSelectElements("PoductDetails/Item"))
        {
            string itemname = xNode.Attribute("Name").Value;
        }

No comments:

Post a Comment