Đoạn mã ví dụ trong tài liệu MSDN đối với phương pháp XNode.ReadFrom
là như sau:
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);
}
}
Nhưng tôi đã phát hiện ra rằng StreamRootChildDoc
phương pháp trong ví dụ này cần phải được sửa đổi như sau:
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();
}
}
}
}
Nguồn
2013-08-16 20:59:12
rực rỡ. Tôi đang phát triển một ứng dụng sẽ xử lý nhiều tệp XML 200M và XDocument đã giết tôi. điều này đã thực hiện một cải tiến lớn. cảm ơn. –
Tôi nghĩ có một lỗi trong mã ví dụ trên trang tài liệu 'XNode.ReadFrom'. Câu lệnh 'XElement el = XElement.ReadFrom (reader) là XElement;' nên là 'XElement el = new XElement (reader.Name, reader.Value);' thay vào đó. Như là, đầu tiên của mỗi hai phần tử 'Child' được bỏ qua trong tệp XML mà từ đó nó đọc. –
Nhận xét cuối cùng của tôi không hoàn toàn chính xác; làm việc trên này ngay bây giờ cho bản thân mình ... –