**
情景一:xml中存着一个参数,你仅仅是想用这个参数而已c#代码:
using System.IO;
using System.Xml;
using UnityEngine;
public void LoadXml(string XmlPath)
{
XmlDocument xd = new XmlDocument();
xd.Load("XmlPath");//加载xml文档
XmlNode rootNode = xd.SelectSingleNode("RootNode");//得到xml文档的根节点
XmlNode node = rootNode.SelectSingleNode("EndTime");//获取根节点的子节点"EndTime"
string time = node.InnerText;
print(time);
}
Xml文本内容
30
运行 成功
代码:
using System;
using System.Threading;
using System.Xml;
using System.Collections.Generic;
public static void Main(string[] args){
XmlDocument xd=new XmlDocument();
xd.Load("test.xml");//加载xml文档
XmlNode rootNode= xd.FirstChild;//得到xml文档的根节点
XmlNodeList childNodes= rootNode.ChildNodes;//得到根节点下面的所有子节点
List playerList=new List();//创建character类型的列表
foreach(XmlNode p in childNodes){//遍历各个角色
Character player=new Character();//创建一个角色,用来存储查询到的信息
XmlNodeList contentList= p.ChildNodes;//得到该角色结点下的所有子节点
foreach(XmlNode content in contentList){//遍历子节点
if(content.Name=="name"){
player.Name=content.InnerText.ToString();
}
if(content.Name=="profession"){
player.Profession=content.InnerText.ToString();
}
if(content.Name=="skill"){
player.Skill=content.InnerText.ToString();
}
if(content.Name=="damage"){
player.Damage=Int16.Parse( content.InnerText.ToString());
}
}
playerList.Add(player);//将创建的角色添加到角色列表
}
foreach(Character p in playerList)//遍历角色信息
Console.WriteLine(p.ToString());
Console.ReadKey();
}
class Character{
public Character(){}
public string Name{get;set;}
public string Profession{get;set;}
public string Skill{get;set;}
public int Damage{get;set;}
public override string ToString()
{
return string.Format("[Character Name={0}, Profession={1}, Skill={2}, Damage={3}]", Name, Profession, Skill, Damage);
}
}
XML文本内容:
武则天法师生杀予夺1100
吕布战士神魔降世900
孙悟空刺客如意金箍770
妲己法师女王崇拜485
运行结果:
成功!
三.读取XML文件各节点方式XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("XMLConfig.xml");
XmlNode xmlRoot = xmlDocument.SelectSingleNode("Root");
XmlNode xmlChild1 = xmlRoot.SelectSingleNode("Child1");
XmlNode xmlChild2 = xmlRoot.SelectSingleNode("Child2");
Console.WriteLine("xmlChild2.InnerText is:" + xmlChild2.InnerText);
XmlNode xmlChild3 = xmlRoot.SelectSingleNode("Child3");
XmlNode xmlChild3Child = xmlChild3.SelectSingleNode("Child3的XmlElementInner");
foreach (XmlAttribute value in xmlChild3Child.Attributes)
{
Console.WriteLine(value.Name + " " + value.Value);
}
Console.WriteLine("xmlChild3Child.InnerText is:" + xmlChild3Child.Attributes.GetNamedItem("我是键").Value);
我是Child2的值呀
四:补充 xml节点类型
读取方式
string type = book.GetAttribute("Type").ToString();
感谢原文作者:https://blog.csdn.net/hyy_sui_yuan/article/details/81263995###
如果想学习 C#对Xml文件的增、删、改、查 请看这篇博文:https://blog.csdn.net/weixin_45023328/article/details/108149781