C# 如何用linq生成XML文件,子节点要带属性。

C# 如何用linq生成XML文件,子节点要带属性。,第1张

linq是用来查询的,生成和他没什么关系。

public void WriteXml(string path)

        {

            XElement eleRoot = new XElement("Config")

            察庆XElement eleParams=new XElement("Params",new XAttribute("type","SerialPoart_Param"))

            for (int i = 0 i < 100 i++)

          猛谨  {

                eleParams.Add(new XElement("Param", new XAttribute("name", "Port"),"COM"+(i+1)))

            }

            eleParams.Add(new XElement("Param"败知握,new  XAttribute("name","BaundRate"),"9600"))

            eleRoot.Add(eleParams)

            File.WriteAllText(path, eleRoot.ToString())

        }

新建一个Log.txt文件薯旅

引入System.IO名称空间,用文件流

using System

using System.Collections.Generic

using System.Linq

using System.Text

using System.IO

namespace StreamWrite

{

class Program

{

static void Main(string[] args)

{

try

{

FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate)

StreamWriter sw = new StreamWriter(aFile)

bool truth = true

// Write data to file.

sw.WriteLine("Hello to you.")

sw.WriteLine("It is now {0} and things are looking good.",

DateTime.Now.ToLongDateString())

sw.Write("More than that,")

sw.Write(" it's {0} that C# is fun.", truth)

sw.Close()

}

catch (IOException ex)

{

Console.WriteLine("An IOException has been thrown!")

Console.WriteLine(ex.ToString())

Console.ReadLine()

return

}

}

}

}

读取文件,这数型凳里介绍StreamReader对象

static void Main(string[] args)

{

string strLine

try

{

FileStream aFile = new FileStream("Log.txt",FileMode.Open)

StreamReader sr = new StreamReader(aFile)

strLine = sr.ReadLine()

//Read data in line by line 这个兄台看的懂吧~一行一行的读取

while(strLine != null)

{

Console.WriteLine(strLine)

Line = sr.ReadLine()

}

sr.Close()

}catch (IOException ex)

{

Console.WriteLine("An IOException has been thrown!")

Console.WriteLine(ex.ToString())

Console.ReadLine()

return

}

}

另外对于简单的文档可以直接sr.ReadToEnd()从头读到尾,还有sr.Read() 返回类型char。这些租岁兄台可以自己看书去学


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12201072.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存