【问题标题】:Use for loop when writing a XML file with LINQ使用 LINQ 编写 XML 文件时使用 for 循环
【发布时间】:2014-01-29 13:16:09
【问题描述】:

我必须将数据保存到 XML 文件中,数据存储在 4 个数组和 2 个 int 中。我必须使用每个数组中的相同元素(例如 candTur1[0]votTur1[0]

我试过使用这个代码:

XDocument document = new XDocument(
   new XDeclaration("1.0", "utf-8", "yes"),
   new XElement("alegeri",
       new XElement("tur",
           new XElement("nrtur", 1),
           for (int i = 0; i < candTur1.Length; i++)
           {
               new XElement("candidat",
               new XElement("nume", candTur1[i]),
               new XElement("voturi",votTur1[i] ),
               new XElement("procent",((votTur1[i] * 100) / votanti)) );
           };
         );
       );
    document.Save("People.xml");

所有数组都具有相同的长度,并且 XML 应如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<alegeri>
  <tur>
    <nrtur>1</nrtur>
    <alegatori>2341</alegatori>
    <candidat>
      <nume>Ion</nume>
      <voturi>50</voturi>
      <procentaj>50</procentaj>
    </candidat>
  </tur>
  <tur>
    <nrtur>2</nrtur>
    <alegatori>2341</alegatori>
    <candidat>
      <nume>Ion</nume>
      <voturi>50</voturi>
      <procentaj>50</procentaj>
    </candidat>
  </tur>
</alegeri>

谢谢!

【问题讨论】:

  • 你的方法有什么问题,你遇到了什么错误?
  • 您希望生成的 xml 看起来如何?
  • 这在我看来就像XmlSerializer 工作。你介意用它来serialize(写)文件吗?作为奖励,您可以 反序列化(读取)它,这两个操作都需要 2 行代码。

标签: c# xml arrays linq


【解决方案1】:

你可以这样做:

XDocument document = new XDocument(
   new XDeclaration("1.0", "utf-8", "yes"),
   new XElement("alegeri",
       Enumerable.Range(1,2).Select(i => 
         new XElement("tur",
           new XElement("nrtur", i),
             candTur1.Select((s, index) =>                
                new XElement("candidat",
                new XElement("nume", candTur1[index]),
                new XElement("voturi",votTur1[index] ),
                new XElement("procent",((votTur1[index] * 100) / votanti)) ))))));

我不知道数组长什么样,但这段代码假定所有数组的长度相同。

【讨论】:

  • 是的,它们的长度都是一样的。
  • 我已经更新了我的答案以生成您描述的 XML。
  • 从您的示例开始,我能够理解逻辑并修改代码以生成所需的 XML。感谢您的时间和精力。
【解决方案2】:

要扩展@Håkan Fahlstedt 的答案,XElement 可以接受子元素的IEnumerable。因此,只要您可以创建一系列子元素,您就可以将其传递给您想要的任何元素。

所以要重写你的例子,我可以首先有一个循环遍历数组的方法:

private IEnumerable<XElement> GetArraySequence()
{
    for (int i = 0; i < candTur1.Length; i++)
    {
        yield return new XElement("candidat",
            new XElement("nume",candTur1[i]),
            new XElement("voturi",votTur1[i] ),
            new XElement("procent", ((votTur1[i] * 100) / votanti))
        );
    };
}

然后您可以按如下方式创建您的 XML 文档:

XDocument document = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("alegeri",
        new XElement("tur",
            new XElement("nrtur", 1)),
            GetArraySequence()
    ));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多