0

XML file Format:

    <pl>
     <afs> 
      <af id="1"></af>  
       <af id="2"></af>
     </afs>
     <pss>
      <ps>
       <a>
        <x afid="1"> </x>
        <x afid="2"> </x>
       </a>
      </ps>
      <ps>
        <a>  
         <x afid="2"></x>
        </a>
      </ps>
    </pss>
   </pl>

For all afs child af nodes, I would like create child x nodes in the parent a node with Attribute values.

I used the following code which is creating only empty elements. I am struck with the comparison, can any one have idea about this. Here is code:

if (this.Xml.Descendants("a").Count() > 0) {
      var cs = this.Xml.Descendants("a").ToList();
      var cCounts = containers.Select(i => i.Elements("x").Count());
      var maxCount = containerCounts.Max();
      var afIds = from actionField in this.Xml.Descendants("af").Attributes().ToList(); // Here i get compiler error --                                                         

      foreach (var c in cs)
      {
        int count = c.Elements("x").Count();
    var xList = c.Descendants("x").ToList();
        foreach (var xlst in xList)
    {
         for (int i = count; i < maxCount; i++)
          {
        c.Add(new XElement("x", new XAttribute("afid", "1"))); // instead 1 I should have correct id value
           }
        }
      }
}

The result I am trying to get is:

  <pl>
         <afs> 
          <af id="1"></af>  
           <af id="2"></af>
         </afs>
         <pss>
          <ps>
           <a>
            <x afid="1"> </x>
            <x afid="2"> </x>
           </a>
          </ps>
          <ps>
            <a> 
             <x afid="1"></x>
             <x afid="2"></x>
            </a>
          </ps>
        </pss>
       </pl>
4

1 回答 1

2

问题是您没有在新元素上设置属性。使用此方法:

public static void ConformDocument(XDocument doc)
{
    var writeElements = doc.Descendants("a").ToList();
    if (writeElements.Count == 0)
        return;

    var root = doc.Descendants("pl");

    var ids = (from afs in root.Descendants("afs")
                from af in afs.Descendants("af")
                from attr in af.Attributes("id")
                select attr.Value).Distinct(StringComparer.Ordinal).ToList();

    var elements = root
        .Descendants("pss")
        .Descendants("ps")
        .Descendants("a")
        .Select(a => new {element = a, aids = a.Descendants("x").Attributes("aid")});

    foreach (var e in elements)
    {
        foreach (var id in ids.Where(id => !e.aids.Any(attr => id.Equals(attr.Value))))
        {
            var element = new XElement("x");
            element.SetAttributeValue("aid", id);
            e.element.Add(element);
        }
    }
}

如果性能成为问题,请告诉我,我会给你一个使用XmlReaderand的版本XmlWriter

于 2013-07-11T21:44:25.887 回答