简体   繁体   English

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

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

I've got a class: 我上课了:

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

How do I read the XML attribute and assign it to int from the class above in the following LINQ query: 如何读取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
    };

Try this instead: 试试这个:

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

This uses the explicit conversion operator available from XAttribute to int , whose MSDN page you can find here . 这使用XAttribute提供的显式转换运算符到int ,您可以在此处找到其MSDN页面。

Now obviously, this will throw a FormatException if the conversion doesn't succeed. 现在显然,如果转换不成功,这将抛出FormatException If that's not what you want, please indicate what you would like to happen. 如果那不是你想要的,请说明你想要发生什么。 It is possible (if somewhat inconvenient) to use int.TryParse here, but it would have to be done differently. 这里使用int.TryParse 可能的(如果有点不方便),但必须以不同的方式完成。

Try Convert.ToInt32 method 尝试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)

or 要么

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

You need Convert.ToInt32 你需要Convert.ToInt32

I would also recommend adding checks to make sure it is an int so that you're not trying convert "three" to an integer. 我还建议添加检查以确保它是一个int,这样你就不会尝试将“三”转换为整数。 But I guess it depends on how much control you have over the xml coming back. 但我想这取决于你对xml回来的控制程度。

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

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