简体   繁体   中英

Writing xml and reading it back c# with xample xml output

Ok I am using again xmldocument to write an xml file then read it back in simple right but how to get the age this time in this example? I was asked to produce the whole problem before so here it is.

        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>

您可以使用以下命令直接在节点上访问属性数组

MessageBox.Show(node.SelectSingleNode("user").Attributes["age"].InnerText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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