LINQ multiple columns

£可爱£侵袭症+ 提交于 2019-12-27 02:07:08

问题


<root>
    <data1>
        <Element1>Value</Element1>
        <Element2>Value</Element2>
        <Element3>Value</Element3>
    </data1>
    <data2>
        <Element1>Value</Element1>
        <Element2>Value</Element2>
    </data2>
</root>

From the above XML I would like to make an XML looking like this:

<root>
    <d1e1>value<d1e1>
    <d1e2>value<d1e2>
    <d2e1>value<d2e1>
</root>

What is the most efficient way to process that? Foreach or Linq in theory Linq should be faster in most cases and speed is of the essence for this project

Any idea?


回答1:


The idea was to just select X nodes out of a pool of Y and the example here is simplified to show you the problem. In general it is like that I have a multi level xml that I needed to flat out to only have one sublevel (aka root + level1) but from the source I only need to have certain elements that are of interest to me.

Anyway the issiue is solved cos I done it with foreach cos I found out that if you have an shema specified in the xml but not accessable LINQ dosent whant to work anyway.

the solution was like this:

  1. I made a function:

    public System.Xml.XmlElement GetSubElement(XmlElement Parent, string element)
    {
     System.Xml.XmlElement ret = null;
     if (Parent == null)
      return ret;
    
     XmlNodeList ContentNodes = Parent.GetElementsByTagName(element);
     if (ContentNodes.Count > 0)
     {
      XmlNode node = ContentNodes.Item(0);
      ret = (XmlElement)node;
     }
    
     return ret;
    }
    
  2. I made a foreach loop on the area that was repeating

  3. I got the elements that where out of the repeating context with the above function.

Anyway that solved it for me.

Edit: Don't know how to get this code to appear properly cos Ctrl+K dosent seem to do it



来源:https://stackoverflow.com/questions/8601074/linq-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!