繁体   English   中英

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

[英]Writing xml and reading it back c# with xample xml output

好的,我再次使用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>

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

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

暂无
暂无

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

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