NET基础学习笔记11---XML学习

XML主要的功能是用来存储数据的。

好处,用文本格式进行保存。不需要安装其他软件打开。

XML和HTML的区别:

1.有且只能有一个根元素。

2.XML中的元素必须关闭。

3.XML中元素的属性值必须用引号。

4.XML大小写敏感。

XML读取

1.获取xml

XDocument xdoc=XDocument.Load("路径");

2.获取根元素

XElement root=xdoc.Root;

3.获取元素.

IEnumerable<XElement>XElements=root.Elements();

4.获取元素

IAttribute Attributeitem-XElementitem.Attributes();

XML写入

1.创建XDocument对象

XDocument xdoc = new XDocument();

2.创建根节点。

XElement root = new XElement("website");
xdoc.Add(root);

//1.第一种创建方法

//添加子节点
 XElement childnode = new XElement("baidu", "百度");
XAttribute url = new XAttribute("url", "www.baidu.com");
childnode.Add(url);
 root.Add(childnode);
//2.第二种创建方法
root.SetElementValue("goole", "谷歌");
root.SetAttributeValue("url", "www.goole.com");
root.SetElementValue("name", "adfads");
childnode.SetElementValue("a333", "asdf");
childnode.SetElementValue("a22", "asdf");
childnode.SetElementValue("a44", "afsd");

3.找节点

1.在根节点直接子元素下搜索

root.Element("元素名称");

2.在根节点下的所有元素中搜索

root.Descandants("元素名称");

隐式转换的定义:public static implicit operator 类型名(转换的方式);

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace _3隐形转换
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Person p = "隐式转换";
            this.Text = p.Name;
        }

        public class Person
        {
            public string Name { set; get; }
            public static implicit operator Person(string name)
            {
                return new Person { Name = name };
            }
        }
    }
}
隐式转换
原文地址:https://www.cnblogs.com/huijie/p/3366993.html