且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用linq- c#将XML元素值转换为int

更新时间:2023-11-07 14:18:16

只需广播XElementint :

private void buttonTab4Mod1Calculate_Click(object sender, EventArgs e)
{
    var document = XDocument.Load(workingDir + @"\Level4.xml");

    string selectedItem = (string) comboBoxTab4Mod8.SelectedItem;
    var assessmentOneWeight = from d in document.Descendants("moduleTitle")
                              where (string) d == selectedItem
                              select (int) d.Parent.Element("assessmentOneWeight");
    foreach (int item in assessmentOneWeight)
    {
         MessageBox.Show(item.ToString());
    }        
}

请注意,您还可以广播到int? 引用XElement时的方法相同,但是如果对int?强制使用空引用,则会返回空值-如果您不知道是否存在空值,这将很有帮助与否是相应的元素.

Note that you can also cast to int? which works the same way when the reference does is an XElement, but if you cast a null reference to int? you get a null value back - which can be helpful if you don't know whether there is a corresponding element or not.

XElementXAttribute也有很多明确的转换-它们使生活变得更加轻松.

There are lots of explicit conversions for XElement, and XAttribute too - they make life a lot easier.