简体   繁体   English

LINQ使用循环添加Xattribute

[英]LINQ to add Xattribute using loop

Here is my sample XML, 这是我的示例XML,

 <A>
    <B  id="ABC">
      <C name="A" />
      <C name="B" />
      <C name="C" />
      <C name="G" />
    </B>
    <B id="ZYZ">
      <C name="A" />
      <C name="B" />
      <C name="C" />
      <C name="D" />
    </B>
  </A>

I need to loop each of the <B> nodes under parent <A> and add a sequence numbered Xattribute called Sno to the <C> tag for each <B> as shown below, 我需要循环在父<A>下的每个<B>节点,并为每个<B><C>标记添加一个名为Sno的序列号Xattribute ,如下所示,

 <A>
    <B  id="ABC">
      <C name="A" Sno ="1" />
      <C name="B" Sno ="2"/>
      <C name="C" Sno ="3"/>
      <C name="G" Sno ="4"/>
    </B>
    <B id="ZYZ">
      <C name="A" Sno ="1"/>
      <C name="B" Sno ="2"/>
      <C name="C" Sno ="3"/>
      <C name="D" Sno ="4"/>
    </B>
  </A>

Using following c# code, 使用以下c#代码,

var final = from x in afterGrouping.Descendants("A").Descendants("B").Select((sc, i) => new {sc, sequence = i + 1})
                                select new XElement("C",
                                                    new XAttribute("id", x.sc.Element("C").Attribute("id").Value),
                                                    new XAttribute("sequence", x.sequence));

It might be easier to use a loop to alter the current document, rather than project one anew: 使用循环来更改当前文档可能比重新设计一个更容易:

foreach (XElement b in xDoc.Descendants("B"))
{
    int seq = 1;
    foreach (XElement c in b.Elements("C"))
        c.Add(new XAttribute("Sno", seq++));
}

Something like this should do the trick: 这样的事情应该可以解决问题:

using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            const string xml = @"<A><B  id='ABC'><C name='A' /><C name='B' /><C name='C' /><C name='G' /></B><B id='ZYZ'><C name='A' /><C name='B' /><C name='C' /><C name='D' /></B></A>";
            var doc = XDocument.Parse(xml);

            var bs = doc.Descendants("B");

            foreach (var r in bs)
            {
                var cs = r.Descendants("C");

                var xElements = cs as XElement[] ?? cs.ToArray();
                for (var i = 1; i <= xElements.Count(); i++)
                {
                    var c = xElements.ElementAt(i-1);
                    c.SetAttributeValue("Sno", i);
                }
            }

            var resultingXml = doc.ToString();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM