创建XML文档
static void Main(string[] args){//1.引入命名空间//2.创建XML文档对象XmlDocument xmldoc = new XmlDocument();//3.创建第一行描述信息,添加到xmldoc文档中XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);xmldoc.AppendChild(xmldec);//4.创建根节点,xml文档有且只能有一个根节点XmlElement xmlele1 = xmldoc.CreateElement("Books");//5.将根节点添加到xmldoc文档中 xmldoc.AppendChild(xmlele1);//6.创建子节点XmlElement xmlele2 = xmldoc.CreateElement("Book");//7.将子节点添加到根节点 xmlele1.AppendChild(xmlele2);//6.将子节点添加到子节点XmlElement name = xmldoc.CreateElement("Name");name.InnerText = "c#从入门到精通";xmlele2.AppendChild(name);XmlElement author = xmldoc.CreateElement("Author");author.InnerText = "Holliszzz";xmlele2.AppendChild(author);XmlElement price = xmldoc.CreateElement("Price");price.InnerText = "99";xmlele2.AppendChild(price);//属性XmlElement xmlele3 = xmldoc.CreateElement("Pen");xmlele1.AppendChild(xmlele3);XmlElement item = xmldoc.CreateElement("Ttem");item.SetAttribute("材质", "金子");item.SetAttribute("颜色", "黄色");xmlele3.AppendChild(item);xmldoc.Save("Books.xml");Console.WriteLine("创建成功");Console.ReadKey();}
XML常用属性方法
static void Main(string[] args){//1.XmlDocument类实例化XmlDocument xmldoc = new XmlDocument();//2.导入指定xml文件xmldoc.Load("");//3.获取指定节点XmlNode xmlnode = xmldoc.SelectSingleNode("");//4.获取指定节点下所有子节点XmlNodeList nodelist1 = xmlnode.ChildNodes;//5.获取同级同名所有节点XmlNodeList nodelist2 = xmldoc.SelectNodes("");//6.判断指定节点下是否有子节点bool b = xmlnode.HasChildNodes;//7.创建一个节点XmlElement xmlelement = xmldoc.CreateElement("");//8.为指定节点下添加子节点 xmlnode.AppendChild(xmlelement);//9.为指定节点添加属性并赋值xmlelement.SetAttribute("", "");//10.获取指定节点属性值string s1 = xmlelement.Attributes[""].Value;//11.获取指定节点文本string s2 = xmlelement.InnerText;//12.保存xml文件xmldoc.Save("");}