문제

큰 XML 파일 (100+m)을 읽고 싶습니다. 크기로 인해 Xlement를 사용하여 메모리에로드하고 싶지 않습니다. LINQ-XML 쿼리를 사용하여 구문 분석하고 읽습니다.

가장 좋은 방법은 무엇입니까? LINQ-XML/Xlement와 XPATH 또는 XMLREADER의 조합에 대한 예?

도와주세요. 감사.

도움이 되었습니까?

해결책

예, XMLREADER를 THE와 결합 할 수 있습니다 메소드 xnode.readfrom, C#을 사용하여 XMLREADER에서 발견 한 노드를 Xlement로 선택적으로 처리하는 문서의 예를 참조하십시오.

다른 팁

MSDN 문서의 예제 코드 XNode.ReadFrom 방법은 다음과 같습니다.

class Program
{
    static IEnumerable<XElement> StreamRootChildDoc(string uri)
    {
        using (XmlReader reader = XmlReader.Create(uri))
        {
            reader.MoveToContent();
            // Parse the file and display each of the nodes.
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (reader.Name == "Child")
                        {
                            XElement el = XElement.ReadFrom(reader) as XElement;
                            if (el != null)
                                yield return el;
                        }
                        break;
                }
            }
        }
    }

    static void Main(string[] args)
    {
        IEnumerable<string> grandChildData =
            from el in StreamRootChildDoc("Source.xml")
            where (int)el.Attribute("Key") > 1
            select (string)el.Element("GrandChild");

        foreach (string str in grandChildData)
            Console.WriteLine(str);
    }
}

그러나 나는 그것을 발견했다 StreamRootChildDoc 예제의 메소드는 다음과 같이 수정해야합니다.

    static IEnumerable<XElement> StreamRootChildDoc(string uri)
    {
        using (XmlReader reader = XmlReader.Create(uri))
        {
            reader.MoveToContent();
            // Parse the file and display each of the nodes.
            while (!reader.EOF)
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Child")
                {
                    XElement el = XElement.ReadFrom(reader) as XElement;
                    if (el != null)
                        yield return el;
                }
                else
                {
                    reader.Read();
                }
            }
        }
    }

파일을 순차적으로 읽어야하고 형제 자매 나 후손을 언급하는 것은 최악의 상황에서 가장 느리고 불가능할 것임을 명심하십시오. 그렇지 않으면 @martinhonnn에 열쇠가 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top