Xml 文件读写操作

XML文档

<?xml version="1.0" encoding="utf-8"?>
<System>
  <Config version="1.0">
    <UserName>admin</UserName>
    <Password>lIG4NadgtDc=</Password>
    <FilePath>D:\123\</FilePath>
  </Config>
</System>
System,Config ,UserName.... 都属于 XmlElement
version 属于 Attribute

Xml文件加载

XmlDocument file = new XmlDocument();
file.Load(Path);

 

获取元素   XmlElement

// 获取根元素
XmlElement xmlMian = file.DocumentElement;
// 获取根元素下级元素
XmlElement ScanBox = xmlMian["Config"]["UserName"];

 

获取属性    Attribute

// 先获取元素,再去元素中查找属性
XmlElement Config = file.DocumentElement["Config"];

string version = Config.GetAttribute("version");

 

获取元素中内容

XmlElement Password = xmlMian["Config"]["Password"];

string PasswordVlue = Password.InnerText;

 

添加元素

// 先创建元素
XmlElement element= file.CreateElement("price");

// 添加元素到一个元素的下级
XmlElement Config = file.DocumentElement["Config"];
Config.AppendChild(element);

// 元素内赋值
Config["price"].InnerText="29.95";

 

添加属性

XmlAttribute xmlAttribute = file.CreateAttribute("Date");
xmlAttribute.Value = DateTime.Now.ToString();

Config.SetAttributeNode(xmlAttribute);

 

结果

<System>
  <Config version="1.0" Date="2021/6/24 14:50:04">
    <UserName>admin</UserName>
    <Password>password</Password>
    <FilePath>D:\123\</FilePath>
    <price>29.95</price>
  </Config>
</System>

 

循环获取

<System>
  <Config>
    <ItemShow>
      <item>
        <name>状态</name>
        <EnglishName>RunState</EnglishName>
        <value>1</value>
      </item>
      <item>
        <name>电压</name>
        <EnglishName>Voltage</EnglishName>
        <value>1</value>
      </item>
      <item>
        <name>电流</name>
        <EnglishName>Current</EnglishName>
        <value>1</value>
      </item>
    </ItemShow>
  </Config>

<item>
<name>测试</name>
<EnglishName>Test</EnglishName>
<value>0</value>
</item>

</System>

 

ObservableCollection<MonomerShowItem> ShowItem = new ObservableCollection<MonomerShowItem>();
// 文件加载 XDocument xDoc
= XDocument.Load(Definition.ConfigPath);

// 获取所有item元素,不管在那个元素下都会获取
var TestItemList = xDoc.Descendants("item"); foreach (var item in TestItemList) { MonomerShowItem item1 = new MonomerShowItem(); item1.Name = item.Element("name").Value; item1.IsShow = int.Parse(item.Element("value").Value) == 1 ? true:false; ShowItem.Add(item1); }

 

posted @ 2021-06-24 14:53  妖言惑众'  阅读(125)  评论(0)    收藏  举报