首先在根目录下新建一个config.xml:
XmlDocument位于System.Xml 下,是专门处理xml节点的
XElement位于System.Xml.Linq下,是可以对xml进行linq的查询操作的
分别使用XmlDocument和XElement获取节点的值:
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
namespace FileXml
{
class Program
{
static void Main(String[] args)
{
//获取xml路径
var current_dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var xml_path = Path.Combine(current_dir, @"config.xml");
//使用XElement快速获取节点值
XElement xmlElement = XElement.Load(xml_path);
String IP = xmlElement.Element("Debug").Element("Lan").Element("Server").Attribute("Ip").Value.ToString();
Console.WriteLine(IP);
bool isLogger = xmlElement.Element("Debug").Element("Logger").Attribute("enable").Value == "true";
Console.WriteLine(isLogger);
//使用XElement快速获取节点值
XmlDocument xml_doc = new XmlDocument();
xml_doc.Load(xml_path);
var IP2 = xml_doc.SelectSingleNode("/Config/Debug/Lan/Server").Attributes["Ip"].Value;
var IP2_name = xml_doc.SelectSingleNode("/Config/Debug/Lan/Server").Attributes["Ip"].Name;
Console.WriteLine(IP2_name+":"+ IP2);
bool isLogger2 = xml_doc.SelectSingleNode("/Config/Debug/Logger").Attributes["enable"].Value == "true";
Console.WriteLine(isLogger2);
Console.ReadLine();
}
}
}
总结:如果是简单查询 总体上来说两者差不多
感觉还是XmlDocument.SelectSingleNode(XPath)更方便一些
普通用XmlDocument就够了
Xml单例管理类:
using System;
using System.IO;
using System.Reflection;
using System.Xml;
namespace FileXml
{
class Program
{
static void Main()
{
var ip = XmlManager.instance.XmlDoc.SelectSingleNode("/Config/Debug/Lan/Server").Attributes["Ip"].Value;
var ip_name = XmlManager.instance.XmlDoc.SelectSingleNode("/Config/Debug/Lan/Server").Attributes["Ip"].Name;
Console.WriteLine($"{ip_name} : {ip}");
bool isLogger = XmlManager.instance.XmlDoc.SelectSingleNode("/Config/Debug/Logger").Attributes["enable"].Value == "true";
Console.WriteLine(isLogger);
Console.ReadLine();
}
}
public class XmlManager
{
private static XmlManager _instance = null;
public static XmlManager instance
{
get
{
if (_instance == null)
{
return new XmlManager();
}
return _instance;
}
}
private XmlDocument _xml_doc = null;
public XmlDocument XmlDoc
{
get
{
if (_xml_doc == null)
{
var current_dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var xml_path = Path.Combine(current_dir, @"config.xml");
_xml_doc = new XmlDocument();
_xml_doc.Load(xml_path);
}
return _xml_doc;
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/148371.html