Home > Back-end >  LINQ to read XML String and put into a variable
LINQ to read XML String and put into a variable

Time:10-14

I am trying to read XML using LINQ. Previously I use XMLDocument to read but it gives an error and someone on StackOverflow encourage me to use LINQ.

Below is the code i previously used for the XMLDocument

            string soapmessage = @"<?xml version=""1.0"" encoding=""UTF - 8""?>"   "\n"   response.Content;

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(soapmessage);  //loading soap message as string 

            XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);

            manager.AddNamespace("d", "http://tempuri.org/");
            manager.AddNamespace("bhr", "http://52.187.127.196:5000/api/gsowebservice.asmx");

            XmlNodeList xnList = xml.SelectNodes("//bhr:FourMonthsAhead1Response", manager);
            int nodes = xnList.Count;
            string Status = xnList[0]["FourMonthsAhead1Result"]["PlantForecastIntervals"]["PlantForecastIntervalNode"]["IntervalStartTime"].InnerText;
            Console.WriteLine(Status);
            Console.ReadLine();

I am trying to get the <IntervalStartTime> from the first <PlantForecastIntervalNode> into a datetime variable;

Below attaced the XML im trying read:

enter image description here

Below is some of the XML code. I can't paste it here because the code is 2322 lines long so I shortened the code to this.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <s:Body>
        <FourMonthsAhead1Response xmlns="http://tempuri.org/">
            <FourMonthsAhead1Result xmlns="LSS.solar.webservice">
                <PlantDescription xmlns="http://base.datacontract">*PlantName*</PlantDescription>
                <PlantForecastIntervalsCount xmlns="http://base.datacontract">2976</PlantForecastIntervalsCount>
                <ForecastStartDate xmlns="http://base.datacontract">2021-10-08T13:35:55.912612</ForecastStartDate>
                <ForecastEndDate xmlns="http://base.datacontract">2021-10-08T13:35:55.9126123</ForecastEndDate>
                <PlantForecastIntervals xmlns="http://base.datacontract">
                    <PlantForecastIntervalNode>
                        <IntervalStartTime>2021-10-01T00:00:00</IntervalStartTime>
                        <IntervalEndTime>2021-10-01T00:15:00</IntervalEndTime>
                        <IntervalLength>15</IntervalLength>
                        <ForecastResultParameter>FourMonthsAhead1</ForecastResultParameter>
                        <ForecastValue>0</ForecastValue>
                        <ValueUnit>MW</ValueUnit>
                    </PlantForecastIntervalNode>
                    <PlantForecastIntervalNode>
                        <IntervalStartTime>2021-10-01T00:15:00</IntervalStartTime>
                        <IntervalEndTime>2021-10-01T00:30:00</IntervalEndTime>
                        <IntervalLength>15</IntervalLength>
                        <ForecastResultParameter>FourMonthsAhead1</ForecastResultParameter>
                        <ForecastValue>0</ForecastValue>
                        <ValueUnit>MW</ValueUnit>
                    </PlantForecastIntervalNode>
                </PlantForecastIntervals>
            </FourMonthsAhead1Result>
        </FourMonthsAhead1Response>
    </s:Body>
</s:Envelope>

Update

After exploring other threads on StackOverflow I come up with this line below but receive another error of System.UriFormatException: 'Invalid URI: The Uri string is too long.':

XDocument xdoc = XDocument.Load(soapmessage);

            var ids = xdoc.Element("FourMonthsAhead1Result")
                 .Elements("PlantForecastIntervals")
                 .Elements("<PlantForecastIntervalNode>")
                 .Select(item => item.Element("IntervalStartTime").Value);
            Console.WriteLine(ids);

CodePudding user response:

Try this using LINQ

var response = File.ReadAllText("XMLFile1.xml");
var xe = XElement.Parse(response);
XNamespace ns = "http://base.datacontract";
var obj = xe.Descendants(ns   "PlantForecastIntervals")
            .Descendants(ns   "PlantForecastIntervalNode")
            .Select(x => x.Element(ns   "IntervalStartTime").Value);
Console.WriteLine(obj);

CodePudding user response:

Look at below solution,

 var xmlRead = File.ReadAllText(@"XMLFile1.xml"); /// Add your xml file path
        var xElement = XElement.Parse(xmlRead);
        XNamespace xNamespace = "http://base.datacontract";
        var obj = xElement.Descendants(xNamespace   "PlantForecastIntervals")
                    .Descendants(xNamespace   "PlantForecastIntervalNode")
                    .Select(x => x.Element(xNamespace   "IntervalStartTime").Value);

        string[] dateTime = obj.ToArray();
    
        foreach (string x in dateTime)
        {
            Console.WriteLine(x.ToString()); /// it will print time from all IntervalStartTime tags
        }
  • Related