几种最最简单的解析XML的示例代码

        private void button1_Click(object sender, EventArgs e)
        {

            string xml = @"
                            1项目1
                            2项目2
                            3项目3
                            4项目4
                       
";

            // 找出 ID = 2 的项目名
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string xpath = "//row[id=2]/name"; //两个斜杠表示不在乎具体层级

            XmlNode node = doc.SelectSingleNode(xpath);

            if (node != null)
            {
                MessageBox.Show(node.InnerText);
            }           
        }

 

        private void button2_Click(object sender, EventArgs e)
        {
            string xml = "<员工基本信息><姓名>张三<性别>男<年龄>22岁";

            // 解析年龄
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            string xpath = "/员工基本信息/年龄";

            XmlNode node = doc.SelectSingleNode(xpath);

            if (node != null)
            {
                MessageBox.Show(node.InnerText);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string xml = @"
                            项目1
                            项目2
                            项目3
                       
";

            // 找出 row id = 2对应的name
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string xpath = "//row[@id=2]/name";

            XmlNode node = doc.SelectSingleNode(xpath);

            if (node != null)
            {
                MessageBox.Show(node.InnerText);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string xml = @"
                            项目1
                            项目2
                            项目3
                       
";

            // 找出 row id = 2对应的pm
          
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            string xpath = "//row[@id=2]/name";

            XmlNode node = doc.SelectSingleNode(xpath);

            if (node != null)
            {
                if (node.Attributes["pm"] != null)
                    MessageBox.Show(node.Attributes["pm"].Value.ToString());
                else
                    MessageBox.Show("未找到PM属性。");
            }
        }

你可能感兴趣的:(C#,-,其他)