C# 使用Linq读取XML文件

C# 使用Linq读取XML文件,c#,xml,linq,C#,Xml,Linq,我已经到处找了,但只能找到文件中有子元素且没有属性的结果!我从我以前的一篇文章中得到一些建议,使用Linq写入文件,我做到了 if (System.IO.File.Exists("Guardian.re") == false) { //.re is the file extension that is used XDocument doc = new XDocument( new XElement("Guardian", new XAttribute("

我已经到处找了,但只能找到文件中有子元素且没有属性的结果!我从我以前的一篇文章中得到一些建议,使用Linq写入文件,我做到了

if (System.IO.File.Exists("Guardian.re") == false)
{
    //.re is the file extension that is used

    XDocument doc = new XDocument(
      new XElement("Guardian",
      new XAttribute("IGN",IGN),
      new XAttribute("Hours",hours),
      new XAttribute("Why",WhyRank),
      new XAttribute("Qualifications",Qualify)
       )
     );
}
下面是我让它生成的XML

<?xml version="1.0" encoding="utf-8"?>
<Guardian>
  <IGN>IGN</IGN>
  <Hours>Hours</Hours>
  <Why>Why</Why>
  <Qualifications>Qualifications</Qualifications>
</Guardian>

我最近为我的MenuStrip for WinForms编写了一个自定义XML解析方法(它有数百项,XML是我最好的选择)。这可能不是Linq,但以下是我是如何做到的(可能有用):

是根;
是一个子元素;
name=“…”
是XElement的X属性

您似乎希望显示的项目是元素名称、属性名称和属性值的混合体。如果您可以控制xml生成过程,那么在列表中创建您想要的所有元素作为单个元素会容易得多,然后,您所需要做的就是使用LINQ查询所有元素。

您不能将
xml
加载到
数据集中
,然后操作
列表框的结构
?@Greg什么是数据集?@Greg[SerializableAttribute]公共类数据集:MarshallByValueComponent、IListSource、IXmlSerializable、,ISupportInitializeNotification、ISupportInitialize、ISerializable我如何使用它?@user2678408我不太确定做了哪些更改,但是,在再次查看您已有的内容后,我发现您的代码和“生成的”XML不匹配。代码生成的XML实际上看起来更像这样:
var xdoc = XDocument.Load("Guardian.re"); // load your file
var items = xdoc.Root.Elements().Select(e => (string)e).ToList();
// load the document
// I loaded mine from my C# resource file called TempResources
XDocument doc = XDocument.Load(new MemoryStream(Encoding.UTF8.GetBytes(TempResources.Menu)));

// get the root element
// in your XML example, this would be 'Guardian'
// (var is an auto token, it becomes what ever you assign it)
var elements = doc.Root.Elements();

// iterate through the child elements
foreach (XElement node in elements)
{
     // if you know the name of the attribute, you can call it
     // mine was 'name'
     Console.WriteLine("Loading list: {0}", node.Attribute("name").Value);
     // your code may look something like this:
     // listBox.Items.Add(node.Attribute("IGN").Value);

     // in my case, every child had additional children, and them the same
     // *.Cast<XElement>() would give me the array in a datatype I can work with
     // menu_recurse(...) is just a resursive helper method of mine
     menu_recurse(node.Elements().Cast<XElement>().ToArray()));
}
<?xml version="1.0" encoding="utf-8"?>
<menus>
     <menuset name="main">...</menuset>
     <menuset name="second">...</menuset>
</menus>
var xdoc = XDocument.Load("Guardian.re"); // load your file
var items = xdoc.Root.Elements().Select(e => (string)e).ToList();