[英]C# Parse XML Child Nodes
I have a massive XML file; 我有一个庞大的XML文件; so big that I cant open in with any GUI program. 太大了,我无法使用任何GUI程序打开。
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: 这将返回以下结构的XML:
<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? 我如何才能写出仅编写EventID子节点的函数?
If your xml is big then XmlReader is generally a better option then XmlDocument. 如果您的xml很大,则XmlReader通常比XmlDocument更好。 XmlReader is stream based and don't load complete Xml in memory. XmlReader基于流,并且不会在内存中加载完整的Xml。 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 您可以使用xmlreader的ReadToFollowing方法来实现相同的效果,如下所示: https ://msdn.microsoft.com/zh-cn/library/cc189056(v=vs.95).aspx
You can get elements by XmlLinq in this way: 您可以通过XmlLinq通过以下方式获取元素:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.