0

I have a XML file, organized in a way similar to this:

<People>
    <Person>
        <Name>John</Name>
        <SurName>Smith</SurName>
    </Person>
    <Person>
        <Name>Jack</Name>
        <SurName>Woodman</SurName>
    </Person>
    [...]
</People>
<Professions>
    <Person>
        <SurName>Smith</SurName>
        <Profession>Blacksmith</Profession>
    </Person>
    <Person>
        <SurName>Woodman</SurName>
        <Profession>Lumberjack</Profession>
    </Person>
        [...]
    </Professions>

Ok, here we go. I am parsing this using Xml.Linq and I've got sth like this code:

 foreach (XElement datatype in RepDoc.Element("People").Descendants("Persons"))
 {
     Name=datatype.Element("Name").Value;
     SurName=datatype.Element("SurName").Value;
 }

But, the question is if it is possible to open another foreach, inside another method, starting on the current datatype position without parsing from the beginning again. As if the method inherit the XElement datatype, so I could start parsing from the same <Person>node.

It sounds stupid, but I can't put the original .xml because it is huge and has millions of information that would just confuse us more.

Thanks :)

4

1 回答 1

1

好的,所以我相信您正在寻找yield. 这通常会像这样使用:

public IEnumerable<Person> GetPeople()
{
    foreach (XElement datatype in RepDoc.Element("People").Descendants("Persons"))
    {
        var p = new Person
        {
            Name = datatype.Element("Name").Value,
            SurName = datatype.Element("SurName").Value
        };

        yield return p;
    }
}

然后您可以像这样使用该方法:

foreach (Person p in MyClass.GetPeople())

这样做的好处是您只需要读取尽可能多的 XML 文件,因为如果您跳出外循环,一切都会停止。

于 2013-11-05T14:42:46.637 回答