C# 操作XML文件 XmlDocument和XElement

C# 操作XML文件 XmlDocument和XElement首先在根目录下新建一个config.xml:<?xmlversion=”1.0″encoding=”utf-8″?><Config><Debug><Lan><ServerIp=”142.12.10.123″Port=”9601″/></Lan&g…

大家好,又见面了,我是你们的朋友全栈君。

首先在根目录下新建一个config.xml:

<?xml version="1.0" encoding="utf-8"?>
<Config>
    <Debug>
        <Lan>
            <Server Ip="142.12.10.123" Port="9601"/>
        </Lan>
        <Logger enable="false" />
    </Debug>
</Config>

 

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://javaforall.net/150733.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月19日 下午9:46
下一篇 2022年6月19日 下午9:46


相关推荐

  • RenderControl获取控件输出的HTML

    RenderControl获取控件输出的HTML之前写过一篇文章,通过实现ICallbackEventHandler接口,实现其两个方法。RaiseCallbackEvent实现回调处理,GetCallbackResult实现将处理产生的结果输出到客户端。为了实现页面不刷新,我们在GetCallbackResult方法中可以将前台的控件html通过RenderControl方法获取,并Return到客户端…

    2022年7月20日
    20
  • Stream和parallelStream

    Stream和parallelStreamStream和parallelStreamParallelStreamstreamparallelstreamstream和parallelStream一.什么是Stream?Stream是在Java8新增的特性,普遍称其为流;它不是数据结构也不存放任何数据,其主要用于集合的逻辑处理。二.和Iterator的区别Iterator做为迭代器,其按照一定的顺序迭代遍历集合中的每一个元素,并且对每个元素进行指定的操作。

    2022年7月19日
    16
  • Audio的framecount、framesize、sampleRate计算关系

    Audio的framecount、framesize、sampleRate计算关系Audio的framecount、framesize、sampleRate计算关系

    2022年10月16日
    5
  • uni-app的unipush实现通知栏推送服务全过程「建议收藏」

    uni-app的unipush实现通知栏推送服务全过程「建议收藏」背景说明文档这个事情官方应该提供出来,可惜官方觉得是多余的,免费的东西凭啥给你做好。于是我在这里叙述一下实现消息通知推送的步骤。uni-app官方文档入口https://uniapp.dcloud.io/api/plugins/pushuniPush官方使用指南https://ask.dcloud.net.cn/article/35622推送H5+API接口:https://www….

    2022年6月2日
    999
  • 从char 数据类型到smalldatetime 数据类型的转换导致smalldatetime 值越界

    从char 数据类型到smalldatetime 数据类型的转换导致smalldatetime 值越界
    SQL:
    select*fromdbo.pds_operation_log  where(plan_code=12andcreate_timebetween’1900-01-01’and’2098-12-31′)orderbycreate_time asc
     
    出错:
    消息296,级别16,状态3,第1行
    从char数据类型到smalldatetime数据类型的转换导致smalldatetime值越界。

    2022年5月19日
    40
  • WDA原理分析

    WDA原理分析1、什么是WDAWebDriverAgent是Facebook在17年的SeleniumConf大会上推出了一款新的iOS移动测试框架。下面摘录一段官方对于WebDriverAgent的介绍字段:(官方文档:https://github.com/facebook/WebDriverAgent)WebDriverAgent在iOS端实现…

    2022年7月12日
    20

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号