XmlDocument

作者:追风剑情 发布于:2019-7-1 22:09 分类:C#

示例:

test.xml


<?xml version="1.0" encoding="UTF-8"?>
<root>
	<book name="《三国演义》">内容摘要</book>
	<book name="《水浒专》">内容摘要</book>
</root>


代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XmlTest
{
    class Program
    {
        static void Main(string[] args)
        {
            
            ParseXML("test.xml");

            Console.ReadKey();
        }

        private static void ParseXML(string path)
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(path);

            //选择根节点
            XmlNode root = xml.SelectSingleNode("/root");
            //获取所有子节点
            XmlNodeList childList = root.ChildNodes;

            for (int i=0; i<childList.Count; i++)
            {
                XmlNode node = childList.Item(i);
                if (node.NodeType == XmlNodeType.Comment) //跳过XML中的注释
                    continue;
                Console.WriteLine("节点名称:" + node.Name);
                Console.WriteLine("节点类型:" + node.NodeType.ToString());
                Console.WriteLine("LocalName:" + node.LocalName);
                Console.WriteLine("InnerText=" + node.InnerText);
                Console.WriteLine("value="+node.Value);
                Console.WriteLine("NamespaceURI=" + node.NamespaceURI);
                Console.WriteLine("Prefix=" + node.Prefix);
                Console.WriteLine("BaseURI=" + node.BaseURI);
                Console.WriteLine("IsReadOnly=" + node.IsReadOnly);

                //获取属性
                XmlAttributeCollection attributes = node.Attributes;
                if (attributes != null)
                {
                    XmlAttribute nameAtt = attributes["name"];
                    if (nameAtt != null)
                        Console.WriteLine("name="+nameAtt.Value);
                }
                
                //是否有子节点
                if (node.HasChildNodes)
                {
                }
            }
        }
    }
}


运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号