Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c# - LINQ multiple columns

<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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...