编写xml并使用xample xml输出将其读回c#

时间:2017-06-11 10:00:29

标签: c# xml

好的我再次使用xmldocument编写一个xml文件,然后以简单的方式读回来,但是在这个例子中这次是如何获得年龄的?我被要求在此之前产生整个问题。

        private void button1_Click(object sender, EventArgs e)
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlNode rootNode = xmlDoc.CreateElement("users");
        xmlDoc.AppendChild(rootNode);

        XmlNode userNode = xmlDoc.CreateElement("user");
        XmlAttribute attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "42";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "John Doe";
        rootNode.AppendChild(userNode);

        userNode = xmlDoc.CreateElement("user");
        attribute = xmlDoc.CreateAttribute("age");
        attribute.Value = "39";
        userNode.Attributes.Append(attribute);
        userNode.InnerText = "Jane Doe";
        rootNode.AppendChild(userNode);
        xmlDoc.Save("c:\\temp\\testdoc.xml");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string files = "c:\\temp\\testdoc.xml";

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(files);
        foreach (XmlNode node  in xmlDoc)
        {
            MessageBox.Show(node.SelectSingleNode("user").InnerText);
            MessageBox.Show(node.SelectSingleNode("age").InnerText);

        }

    }
I can read the users name correctly but not the age I get an error.


<users>
 <user age="42">John Doe</user>
 <user age="39">Jane Doe</user>
</users>

1 个答案:

答案 0 :(得分:1)

您可以使用

直接在节点上访问attributes数组
MessageBox.Show(node.SelectSingleNode("user").Attributes["age"].InnerText);