1
public XmlNodeList GetNodes(string _logFilePath, string _strXPathQuery)
        {    
                    objXmlDoc = new XmlDocument();
                    objXmlDoc.Load(_logFilePath);
                    XmlNodeList objxmlNodeList = objXmlDoc.SelectNodes(_strXPathQuery);
                    return objxmlNodeList;
        }

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<AppXmlLogWritter>
<LogData>
<LogID>999992013021110381000001</LogID>
<LogDateTime>20130211103810</LogDateTime>
<LogType>Message</LogType>
<LogFlag>Flag</LogFlag>
<LogApplication>Application</LogApplication>
<LogModule>Module</LogModule>
<LogLocation>Location</LogLocation>
<LogText>Text</LogText>
<LogStackTrace>Stacktrace</LogStackTrace>
</LogData>
</AppXmlLogWritter>

这里的 Xml 文件大小为 1000MB,当我将它加载到 xmlDocument 对象中时,它会给我一个 OutOf memory 异常。因为 XMLDocument 将节点存储到内存中。我使用 Xpath 查询通过 xml 文件过滤节点。然后绑定到 listview 以显示节点。我阅读了有关如何处理大型 XML 文件的文章,他们告诉我使用 XpathQuery。但问题并没有解决。 文件流呢?或任何其他加载大型 xml 文件的想法?*

4

2 回答 2

3

您可以编写一个方法,该方法将使用 aXmlReader分块读取大型 XML 文件。

首先设计一个保存数据的模型:

public class LogData
{
    public string LogID { get; set; }
    public string LogDateTime { get; set; }
    public string LogType { get; set; }
    ...
}

然后是一个解析 XML 文件的方法:

public static IEnumerable<LogData> GetLogData(XmlReader reader)
{
    LogData logData = null;
    while (reader.Read())
    {
        if (reader.IsStartElement("LogData"))
        {
            logData = new LogData();
        }
        if (reader.Name == "LogData" && reader.NodeType == XmlNodeType.EndElement)
        {
            yield return logData;
        }
        if (reader.Name == "LogID")
        {
            logData.LogID = reader.ReadElementContentAsString();
        }
        else if (reader.Name == "LogDateTime")
        {
            logData.LogDateTime = reader.ReadElementContentAsString();
        }
        else if (reader.Name == "LogType")
        {
            logData.LogType = reader.ReadElementContentAsString();
        }
        ...
    }
}

现在您可以只加载您想要显示的元素。例如:

using (var reader = XmlReader.Create("someHugeFile.xml"))
{
    IEnumerable<LogData> data = GetLogData(reader).Skip(10).Take(5);
    // Go ahead and bind the data to your UI
}

您可能想知道的另一件事是,为了有效地实现分页,您的 XML 文件中总共有多少条记录。这可以用另一种方法来完成:

public static int GetTotalLogEntries(XmlReader reader)
{
    var count = 0;
    while (reader.Read())
    {
        if (reader.IsStartElement("LogData"))
        {
            count++;
        }
    }
    return count;
}
于 2013-02-11T08:16:13.430 回答
0

我建议您在将它们发送到流之前压缩 xml 消息,然后在另一端收到它后解压缩它。在 WCF 中,您可以这样做http://www.codeproject.com/Articles/165844/WCF-Client-Server-Application-with-Custom-Authenti#Compression

于 2013-02-11T08:22:20.270 回答