繁体   English   中英

如何在LINQ查询期间将XML属性(字符串)解析为(int)

[英]How to parse XML attribute (string) to (int) during the LINQ query

我上课了:

public class Layout
{
    public int Width { get; set; }
    public int Height { get; set; }
}

如何读取XML属性并将其从上面的类中分配给以下LINQ查询中的int:

var layouts =
    from elem in layoutSummary.Descendants("Layout")
    select new Layout
    {
        // Width = elem.Attribute("Width").Value,  // Invalid cast string to int)
        // Int32.TryParse((string)elem.Attribute("Height").Value, Height) // Doesn't assign Height value to Layout.Height
    };

试试这个:

var layouts =  from elem in layoutSummary.Descendants("Layout")
               select new ComicLayout
               {
                   Width = (int) elem.Attribute("Width"),
                   Height = (int) elem.Attribute("Height")
               };

这使用XAttribute提供的显式转换运算符到int ,您可以在此处找到其MSDN页面。

现在显然,如果转换不成功,这将抛出FormatException 如果那不是你想要的,请说明你想要发生什么。 这里使用int.TryParse 可能的(如果有点不方便),但必须以不同的方式完成。

尝试Convert.ToInt32方法

 select new ComicLayout
    {
         Width = Convert.ToInt32( elem.Attribute("Width").Value),
         Height = Convert.ToInt32(elem.Attribute("Height").Value)
    };
 select new ComicLayout
 {
      Width = elem.Attribute("Width") != null ?
              Convert.ToInt32(elem.Attribute("Width").Value) :
              -1,
      Height = elem.Attribute("Height")  != null ? 
               Convert.ToInt32(elem.Attribute("Height").Value) :
               -1,
 };
Width = int.Parse(elem.Attribute("Width").Value)

要么

int w;
if (int.TryParse(elem.Attribute("Width").Value, out w)
    Width = w;

你需要Convert.ToInt32

我还建议添加检查以确保它是一个int,这样你就不会尝试将“三”转换为整数。 但我想这取决于你对xml回来的控制程度。

暂无
暂无

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

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