简体   繁体   中英

Read XML File Using Linq is not reading element

I am not able to get the value from this xml response, I will appreciate any help.

<Response>
  <Result>
    <Item1>GREEN</Item1>
    <Item2>05/19/2017 22:08:14</Item2>
  </Result>
  <Other>
    <Id>xxxxxxxxxxxxc</Id>
  </Other>
</Response>

What I tried so far but the results is empty

string responseXml = response.ToXML();
XElement doc = XElement.Load(new StringReader(responseXml));
var results = from p in
              doc.Descendants("Result")
              select new
              {
                  item = p.Element("Item1").Value,
              };

foreach (var elm in results)
{
    Console.WriteLine(elm.item);
}

Use Parse instead of load. You may also be getting error due to extra characters in the string. In the string you postged there are single quotes. Not sure if the single quote is in the actual string you are using.

            string responseXml = "<Response>" +
                               "<Result>" +
                                 "<Item1>GREEN</Item1>" +
                                 "<Item2>05/19/2017 22:08:14</Item2>" +
                               "</Result>" +
                               "<Other>" +
                                 "<Id>xxxxxxxxxxxxc</Id>" +
                               "</Other>" +
                             "</Response>";
            XElement doc = XElement.Parse(responseXml);
            var results = from p in
                              doc.Descendants("Result")
                          select new
                          {
                              item = p.Element("Item1").Value,
                          };

            foreach (var elm in results)
            {
                Console.WriteLine(elm.item);
            }

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