简体   繁体   中英

C# Parse XML Child Nodes

I have a massive XML file; so big that I cant open in with any GUI program.

I'm wrtting a little program to parse the information I need out of the document.

I have a function that reads the file and for each node writes to the console:

 XDocument doc = XDocument.Load(@"c:\Events\Import\events.xml");
                var i = 0;


                foreach (XElement el in doc.Root.Elements())
                {

                    i++;
                   Console.WriteLine(el.FirstNode);

                }Console.ReadLine();
                }

This is returning XML of the following structure:

<System>
  <Provider Name='Microsoft-Windows-Security-Auditing' Guid='{54849625-5478-4994-A5BA-3E3B0328C30D}'/>
  <EventID>4907</EventID>
  <Version>0</Version>
  <Level>0</Level>
  <Task>13568</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime='2015-03-29T14:47:06.505465800Z'/>
  <EventRecordID>195943</EventRecordID><Correlation/>
  <Execution ProcessID='808' ThreadID='828'/>
  <Channel>Security</Channel>
  <Computer>somecomputer.com</Computer>
  <Security/>
</System>

How can I mdofiy my function to just write the EventID childnode?

If your xml is big then XmlReader is generally a better option then XmlDocument. XmlReader is stream based and don't load complete Xml in memory. You can achieve the same using ReadToFollowing method of xmlreader as shown here: https://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx

You can get elements by XmlLinq in this way:

 XDocument doc = XDocument.Load(@"c:\Events\Import\events.xml");
         if(doc != null)
         {
            var elements =  from el in doc.Element("System").Elements()
             where el.Name == ("EventID")
             select el;
             foreach (XElement item in elements)
             {
                 Console.WriteLine(item.Value);

             }    
         }

         Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM