首页 > 编程语言 >【C#】文件读取 -- .xml文件读取

【C#】文件读取 -- .xml文件读取

时间:2024-09-25 15:01:46浏览次数:1  
标签:xml 文件 return 读取 C# new path root string

.xml文件读取与写入

[实现效果]

[实现编程]
/// <summary>
/// 创建xml配置
/// </summary>
/// <param name="path">path ,如:x:\\xxxx\\xxx.xml</param>
private void createXmlText(string path)
{
    if (string.IsNullOrEmpty(path))
        return;
    if (File.Exists(path))
        return;
    XDocument document = new XDocument();
    XElement root = new XElement("参数");
    root.Add(new XComment("输入图像:采集算子编号"));
    root.SetElementValue("输入图像", "001");
    root.SetElementValue("X偏移", "1");
    root.SetElementValue("Y偏移", "1");
    root.Add(new XComment("结果图像:图像变量的名称"));
    root.SetElementValue("结果图像", "定位图");
    root.Save(path);
}

/// <summary>
/// 读取xml配置
/// </summary>
/// <param name="path">path ,如:x:\\xxxx\\xxx.xml</param>
/// <returns></returns>
private Config readXml(string path)
{
    if (string.IsNullOrEmpty(path))
        return null;
    if (!File.Exists(path))
        return null;
    XDocument document = XDocument.Load(path);
    XElement root = document.Root;
    //读取配置文件
    XElement inputImageNo = root.Element("输入图像");
    XElement offsetX = root.Element("X偏移");
    XElement offsetY = root.Element("Y偏移");
    XElement resultImageVariableName = root.Element("结果图像");
    //转换
    Config config = new Config();
    config.InputImageNo = inputImageNo.Value;
    config.OffsetX = XmlConvert.ToInt32(offsetX.Value == "" ? "0" : offsetX.Value);
    config.OffsetY = XmlConvert.ToInt32(offsetY.Value == "" ? "0" : offsetY.Value);
    config.ResultImageVariableName = resultImageVariableName.Value;
    return config;
}

internal class Config
{
    public string InputImageNo { get; set; }
    public int OffsetX { get; set; }
    public int OffsetY { get; set; }
    public string ResultImageVariableName { get; set; }
}

[实现编程:序列化的方式]
/// <summary>
/// 保存xml文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="dir">文件目录,如 D:\\Config</param>
/// <param name="name">文件名称,如 config.xml</param>
public bool Save<T>(T list, string dir, string name)
{
    try
    {
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);
        var filePath = System.IO.Path.Combine(dir, name);
        //如果文件存在需要删除,否则会续写,造成格式错误
        if (File.Exists(filePath))
            File.Delete(filePath);
        using (System.IO.StringWriter stringWriter = new StringWriter(new StringBuilder()))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(stringWriter, list);
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(stringWriter.ToString());
            sw.Close();
            fs.Close();
        }
    }
    catch (System.Exception ex)
    {

        return false;
    }
    return true;
}

/// <summary>
/// 读取xml文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path">文件路径,如 D:\\Config\\CameraSetting.xml</param>
/// <returns></returns>
public T Read<T>(string path)
{
    if (!File.Exists(path))
        return default;
    try
    {
        using (TextReader reader = new StreamReader(path))
        {
            var serializer = new XmlSerializer(typeof(T));
            var items = (T)serializer.Deserialize(reader);
            return items;
        }
    }
    catch (System.Exception ex)
    {

    }
    return default;
}

[调用方式 示例]

string path = "D:\\Config\\CameraSetting.xml";
// 读
xxxx = Read<List<Camera>>(path);
// 存
Save(path);

标签:xml,文件,return,读取,C#,new,path,root,string
From: https://www.cnblogs.com/moon-stars/p/18431401

相关文章

  • docker笔记_数据卷、挂载
    docker数据存储概述数据卷(Volumes)特点操作绑定挂载(BindMounts)内存挂载(tmpfs)总结概述镜像构建过程中,所产生的layer都是只读层,只有在创建容器时才会生成一个可写的容器层(contatnerlayer)。如下图:在默认情况下,容器内部创建的所有文件都存储在可写层中。这导致:获取......
  • cisp-pte多少钱考一次?cisp-pte报考费用及报考条件一次说清楚!
    CISP-PTE即注册信息安全专业人员-渗透测试工程师,是目前被业界认可的主流专业攻防领域的资质认证,很多小伙伴都在问:CISP-PTE报考条件是什么?cisp-pte报考费用要多少钱?今天一文给大家说清楚!一、CISP-PTE报名条件CISP-PTE需取得国测中心授权机构的培训合格证明才具备报名资格。除......
  • Java开发:文件上传和下载
    一、文件上传使用MultipartFile类型接收参数;调用上传有两种方式:方式一:使用curl命令curl-F"file=@/data/filename.txt"http://localhost:8080/upload--verbose方式二:使用html,写一个form表单:同样是POST请求,为何文件上传的功能会慢?其中一个原因是,使用multipart/fo......
  • 调查一个osd的rocksdb问题
    开始喜欢ceph的话欢迎关注奋斗的cepher微信公众号阅读更多好文!关于osd的问题总是各种各样,奇奇怪怪,有bug相关的,也有环境相关的,或者是配置相关的,对于osd各种问题的处理,重点在思路,思路对了,问题就好解决了。本篇是一个集群有ssd的osd发生down,这本不是什么值得关注的事,osd的do......
  • 记一次pycharm在使用git提交时需要输入ssh key的密码的问题
    问题描述:从gitlab上拉取了一份代码,长时间为动过,偶然一次提交时发现居然需要输入密码,我试了登录密码和常用密码都报错,无法提交代码 解决方案:1.选择菜单栏的git--管理远程 2.更新远程URL将url更新为git仓库右上角clone里面的http的地址,然后确认即可  3.继续你的......
  • springboot 工程中 SpringApplication.run方法 可以指定加载"applicationContext.xml"
    在SpringBoot应用程序中,SpringApplication.run()方法默认使用自动配置和基于Java的配置(如使用@Configuration注解的类),而不是传统的XML配置文件(如applicationContext.xml)。SpringBoot的设计理念之一就是简化配置,鼓励使用注解和Java配置来代替XML配置。然而,如果你......
  • 思科C9系列netflow配置案例 Cisco catalyst 9000 netflow config template
    flowrecordSW_FLOW_RECORDdescriptionNetFlowrecordformattosendtoSWmatchipv4tosmatchipv4protocolmatchipv4sourceaddressmatchipv4destinationaddressmatchtransportsource-portmatchtransportdestination-portmatchinterfaceinputcolle......
  • Delphi10.3关键字自动填充完成AutoComplete
    声明两个全局变量varaStringList:TStringList;//读取关键字aMemoInput:string;//当前已输入项procedureTSearchReplaceDemoForm.FormCreate(Sender:TObject);beginaStringList:=TStringList.Create;aStringList.LoadFromFile('keyWord.txt');//从文件......
  • COMP3331/9331 Computer Networks and Applications
    COMP3331/9331ComputerNetworksandApplicationsAssignmentforTerm3,2024BitTrickleFileSharing System1. Goal and Learning ObjectivesIn this assignment you will have the opportunity to implement BitTrickle, apermissioned,peer-to- pee......
  • 【每周例题】蓝桥杯 C++ 数树数
    数树数题目数树数题目分析通过图片的二叉树,我们可以发现每一个·分支的L=2a-1R=2a代码#include<iostream>#include<string>usingnamespacestd;chars[50];inta;intmain(){intn,q;cin>>n>>q;for(inti=0;i<q;i++){......