C# 从桌面上的文件读取xml数据

C# 从桌面上的文件读取xml数据,c#,xml,C#,Xml,您好,今天我想了解如何用下面的方式读取xml文件,我还没有找到类似这样或任何类似的方法来模拟我希望如何实现这一点。我有一个具有以下内容格式的xml文件,该文件在下面被禁用 <smallusers> <user id="1"> <name>John</name> <motto>I am john, who are you?</motto> </user> <user id="2"> <name&g

您好,今天我想了解如何用下面的方式读取xml文件,我还没有找到类似这样或任何类似的方法来模拟我希望如何实现这一点。我有一个具有以下内容格式的xml文件,该文件在下面被禁用

<smallusers>
<user id="1">
<name>John</name>
<motto>I am john, who are you?</motto>
</user>
<user id="2">
<name>Peter</name>
<motto>Hello everyone!</motto>
</user>
</smallusers>
<bigusers>
<user id="3">
<name>Barry</name>
<motto>Earth is awesome</motto>
</user>
</bigusers>

约翰
我是约翰,你是谁?
彼得
大家好!
巴里
地球是可怕的
如何将其放入csharp中的两个字符串列表中

  • 将其作为文本文件加载到字符串或StringBuilder中
  • 前缀为,结尾为
  • 然后使用XmlDocument加载xml

  • XML只能有一个根标记。您的输入有多个根。因此,您必须将XML封装在下面类似于根的代码中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.txt";
            static void Main(string[] args)
            {
                string input = File.ReadAllText(FILENAME);
    
                input = string.Format("<Root>{0}</Root>", input);
    
                XElement root = XElement.Parse(input);
    
            }
        }
    }
    ​
    
    使用系统;
    使用System.Collections.Generic;
    使用System.Linq;
    使用系统文本;
    使用System.IO;
    使用System.Xml;
    使用System.Xml.Linq;
    命名空间控制台应用程序1
    {
    班级计划
    {
    常量字符串文件名=@“c:\temp\test.txt”;
    静态void Main(字符串[]参数)
    {
    字符串输入=File.ReadAllText(文件名);
    input=string.Format(“{0}”,输入);
    XElement root=XElement.Parse(输入);
    }
    }
    }
    ​
    
    为什么建议使用XmlDocument而不是XDocument?LINQtoXML是一个比XmlDocument更友好的API,IMO。您希望在每个列表中添加什么?