简体   繁体   English

使用Linq读取XML文件未读取元素

[英]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. 我无法从此xml响应中获取值,我将不胜感激。

<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);
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM