用Linq读取XML文件[英] Reading an XML File With Linq

本文是小编为大家收集整理的关于用Linq读取XML文件的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我已经查看了所有内容,但只能找到文件中包含子元素且没有属性的结果!我从我之前的一篇文章中获得了一些建议,使用 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

推荐答案

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

本文地址:https://www.itbaoku.cn/post/1556894.html

问题描述

I have looked all over but could only find results that had Child Elements in the file and no attributes! I took some advice from a previous post of mine to use Linq to write to the file and I did.

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

Now here is the XML that I had it generate

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

Now, I want to display these values in a listbox as follows

Guardian
IGN
Hours
WhyReason
Qualifications

推荐答案

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