hIp*_*pPy 6 xml xelement xpath linq-to-xml large-files
我想读一个大的xml文件(100 + M).由于它的大小,我不想使用XElement将其加载到内存中.我正在使用linq-xml查询来解析和读取它.
最好的方法是什么?关于XPath或XmlReader与linq-xml/XElement组合的任何示例?
请帮忙.谢谢.
是的,您可以将XmlReader与XNode.ReadFrom方法结合使用,请参阅文档中的示例,该文档使用C#有选择地将XmlReader找到的节点作为XElement处理.
该XNode.ReadFrom
方法的MSDN文档中的示例代码如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但我发现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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6398 次 |
最近记录: |