C#读取xml的属性值

今天学习了如何在c#中读取一个xml的属性值,看了很多种方法,还是最喜欢这种办法:利用xmldocument

试例xml:.

<?xml version="1.0"?>
<tasklist>
    <task id="1" name="lala" type="A" sdate="2021-01-01" fdate="2021-02-04" important="True" />
    <task id="2" name="hehe" type="B" sdate="2021-01-04" fdate="2021-02-06" important="False" />
</tasklist>

代码如下:

XmlDocument doc = new XmlDocument();
doc.Load("info.xml");
if (doc == null){
    MessageBox.Show("error");
    return;
} else {
    XmlElement root = doc.DocumentElement;
    XmlNodeList nodes = root.ChildNodes;
    foreach (XmlNode task in nodes)
    {
        MessageBox.Show(task.Attributes["id"].Value);
    }
}

root是获取了xml的根节点tasklist,nodes是tasklist下所有的子节点(即两个task),Attributes["id"].Value则是id的属性值

之前在网上查的时候看见有大佬是用InnerText,我感觉只有在xml语句是以下这种格式的时候才能用:

<task>
    <id>1</id>
</list>

这样的话直接task.InnerText就可输出1了