문제

다음 줄에 특정 태그 데이터가 포함되어 있는지 테스트하기 위해 한 줄을 읽는 방법이 있습니까?

시작 태그가 있지만 엔드 태그가없는 형식을 다루고 있습니다.

라인을 읽고 싶습니다. 구조물에 추가 한 다음 아래 줄을 테스트하여 새로운 "노드"가 아닌지 확인하고 해당 구조물이 가까워지면 새로 추가하지 않으면 새로 만들지 않으면 새로 만들지 않으면 새로 만들지 않으면 계속 추가하지 않으면 계속 추가하지 않으면 계속 추가하지 않으면 계속 추가하지 않으면 계속 추가하지 않으겠습니다.

내가 생각할 수있는 유일한 해결책은 두 명의 스트림 독자가 동시에 잠금 단계를 따라 곤경에 빠지게하는 것입니다.

엿보기이지만 엿보기가 필요합니다

도움이 되었습니까?

해결책

문제는 기본 스트림도 찾을 수 없다는 것입니다. 스트림 리더 구현을 살펴보면 버퍼를 사용하여 스트림을 찾을 수없는 경우에도 TexTreader.peek ()를 구현할 수 있습니다.

다음 줄을 읽고 내부적으로 버퍼링하는 간단한 어댑터를 작성할 수 있습니다.

 public class PeekableStreamReaderAdapter
    {
        private StreamReader Underlying;
        private Queue<string> BufferedLines;

        public PeekableStreamReaderAdapter(StreamReader underlying)
        {
            Underlying = underlying;
            BufferedLines = new Queue<string>();
        }

        public string PeekLine()
        {
            string line = Underlying.ReadLine();
            if (line == null)
                return null;
            BufferedLines.Enqueue(line);
            return line;
        }


        public string ReadLine()
        {
            if (BufferedLines.Count > 0)
                return BufferedLines.Dequeue();
            return Underlying.ReadLine();
        }
    }

다른 팁

Streamreader.basestream.Position에 액세스하는 위치를 저장 한 다음 다음 줄을 읽고 테스트를 수행 한 다음 라인을 읽기 전에 위치를 찾을 수 있습니다.

            // Peek at the next line
            long peekPos = reader.BaseStream.Position;
            string line = reader.ReadLine();

            if (line.StartsWith("<tag start>"))
            {
                // This is a new tag, so we reset the position
                reader.BaseStream.Seek(pos);    

            }
            else
            {
                // This is part of the same node.
            }

이것은 같은 줄을 찾고 다시 읽는 것입니다. 일부 논리를 사용하면 새로운 태그 시작이 표시되면 기존 구조를 닫고 새 구조를 시작하는 것과 같이이를 피할 수 있습니다. 기본 알고리즘은 다음과 같습니다.

        SomeStructure myStructure = null;
        while (!reader.EndOfStream)
        {
            string currentLine = reader.ReadLine();
            if (currentLine.StartsWith("<tag start>"))
            {
                // Close out existing structure.
                if (myStructure != null)
                {
                    // Close out the existing structure.
                }

                // Create a new structure and add this line.
                myStructure = new Structure();                   
                // Append to myStructure.
            }
            else
            {
                // Add to the existing structure.
                if (myStructure != null)
                {
                    // Append to existing myStructure
                }
                else
                {
                    // This means the first line was not part of a structure.
                    // Either handle this case, or throw an exception.
                }
            }
        }

왜 어려움? 관계없이 다음 줄을 반환하십시오. 새 노드인지 확인하십시오. 그렇지 않은 경우 구조물에 추가하십시오. 그렇다면 새 구조물을 만듭니다.

// Not exactly C# but close enough
Collection structs = new Collection();
Struct struct;
while ((line = readline()) != null)) {
    if (IsNode(line)) {
        if (struct != null) structs.add(struct);
        struct = new Struct();
        continue;
    }
    // Whatever processing you need to do
    struct.addLine(line);
}
structs.add(struct); // Add the last one to the collection

// Use your structures here
foreach s in structs {

}

여기 내가 지금까지가는 것이 있습니다. 나는 줄 라인 경로별로 Streamreader 라인보다 분할 경로를 더 많이 갔다.

나는 더 우아하게 죽는 곳이 몇 개있을 것이라고 확신하지만 지금은 작동하는 것 같습니다.

당신의 생각을 알려주세요

struct INDI
    {
        public string ID;
        public string Name;
        public string Sex;
        public string BirthDay;
        public bool Dead;


    }
    struct FAM
    {
        public string FamID;
        public string type;
        public string IndiID;
    }
    List<INDI> Individuals = new List<INDI>();
    List<FAM> Family = new List<FAM>();
    private void button1_Click(object sender, EventArgs e)
    {
        string path = @"C:\mostrecent.ged";
        ParseGedcom(path);
    }

    private void ParseGedcom(string path)
    {
        //Open path to GED file
        StreamReader SR = new StreamReader(path);

        //Read entire block and then plit on 0 @ for individuals and familys (no other info is needed for this instance)
        string[] Holder = SR.ReadToEnd().Replace("0 @", "\u0646").Split('\u0646');

        //For each new cell in the holder array look for Individuals and familys
        foreach (string Node in Holder)
        {

            //Sub Split the string on the returns to get a true block of info
            string[] SubNode = Node.Replace("\r\n", "\r").Split('\r');
            //If a individual is found
            if (SubNode[0].Contains("INDI"))
            {
                //Create new Structure
                INDI I = new INDI();
                //Add the ID number and remove extra formating
                I.ID = SubNode[0].Replace("@", "").Replace(" INDI", "").Trim();
                //Find the name remove extra formating for last name
                I.Name = SubNode[FindIndexinArray(SubNode, "NAME")].Replace("1 NAME", "").Replace("/", "").Trim(); 
                //Find Sex and remove extra formating
                I.Sex = SubNode[FindIndexinArray(SubNode, "SEX")].Replace("1 SEX ", "").Trim();

                //Deterine if there is a brithday -1 means no
                if (FindIndexinArray(SubNode, "1 BIRT ") != -1)
                {
                    // add birthday to Struct 
                    I.BirthDay = SubNode[FindIndexinArray(SubNode, "1 BIRT ") + 1].Replace("2 DATE ", "").Trim();
                }

                // deterimin if there is a death tag will return -1 if not found
                if (FindIndexinArray(SubNode, "1 DEAT ") != -1)
                {
                    //convert Y or N to true or false ( defaults to False so no need to change unless Y is found.
                    if (SubNode[FindIndexinArray(SubNode, "1 DEAT ")].Replace("1 DEAT ", "").Trim() == "Y")
                    {
                        //set death
                        I.Dead = true;
                    }
                }
                //add the Struct to the list for later use
                Individuals.Add(I);
            }

            // Start Family section
            else if (SubNode[0].Contains("FAM"))
            {
                //grab Fam id from node early on to keep from doing it over and over
                string FamID = SubNode[0].Replace("@ FAM", "");

                // Multiple children can exist for each family so this section had to be a bit more dynaimic

                // Look at each line of node
                foreach (string Line in SubNode)
                {
                    // If node is HUSB
                    if (Line.Contains("1 HUSB "))
                    {

                        FAM F = new FAM();
                        F.FamID = FamID;
                        F.type = "PAR";
                        F.IndiID = Line.Replace("1 HUSB ", "").Replace("@","").Trim();
                        Family.Add(F);
                    }
                        //If node for Wife
                    else if (Line.Contains("1 WIFE "))
                    {
                        FAM F = new FAM();
                        F.FamID = FamID;
                        F.type = "PAR";
                        F.IndiID = Line.Replace("1 WIFE ", "").Replace("@", "").Trim();
                        Family.Add(F);
                    }
                        //if node for multi children
                    else if (Line.Contains("1 CHIL "))
                    {
                        FAM F = new FAM();
                         F.FamID = FamID;
                        F.type = "CHIL";
                        F.IndiID = Line.Replace("1 CHIL ", "").Replace("@", "");
                        Family.Add(F);
                    }
                }
            }
        }
    }

    private int FindIndexinArray(string[] Arr, string search)
    {
        int Val = -1;
        for (int i = 0; i < Arr.Length; i++)
        {
            if (Arr[i].Contains(search))
            {
                Val = i;
            }
        }
        return Val;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top