使用Linq读取XML文件

时间:2013-12-18 21:07:45

标签: 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("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>

现在,我想在列表框中显示这些值,如下所示

Guardian
IGN
Hours
WhyReason
Qualifications

3 个答案:

答案 0 :(得分:0)

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

// 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()));
}

现在,如果您不知道属性的名称,可以通过调用node.Attributes()来获取它,这将返回一个XAttributes数组。此调用将保存给定节点中每个属性的名称和值。 (使用foreach循环)


[编辑]
这是我使用的XML文件(作为演示示例):

<?xml version="1.0" encoding="utf-8"?>
<menus>
     <menuset name="main">...</menuset>
     <menuset name="second">...</menuset>
</menus>

<menus>是根; <menuset>是儿童XElement; name="..."是XElement的XAttribute;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

var xdoc = XDocument.Load("Guardian.re"); // load your file
var items = xdoc.Root.Elements().Select(e => (string)e).ToList();