XmlReader 是 C# 中高效读取大型 XML 文件的最佳方式,采用流式、只进、只读模式避免内存溢出;需通过 XmlReader.Create 配置 DtdProcessing.Ignore、XmlResolver=null 等优化设置,结合 ReadToFollowing/Skip 按需解析,并用 ReadElementContentAsXxx 强类型提取值,配合 using 和异常处理确保健壮性。

C# 中 XmlReader 是读取大型 XML 文件最高效的方式之一,因为它采用**流式、只进、只读**模式,不将整个文档加载到内存,避免了 XDocument 或 XmlDocument 可能引发的内存溢出问题。关键在于正确配置和按需解析节点,跳过无关内容。
使用 XmlReader.Create 配置高性能读取器
直接 new XmlReader 不被允许,必须用 XmlReader.Create() 并传入优化配置:
- 设置
XmlReaderSettings.DtdProcessing = DtdProcessing.Ignore,禁用 DTD 解析(防止外部实体攻击且提速) - 关闭行号/位置信息:
XmlReaderSettings.XmlResolver = null和IgnoreComments = true、IgnoreProcessingInstructions = true、IgnoreWhitespace = true - 若 XML 无命名空间,可设
ProhibitDtd = true进一步加固与加速
按需移动 + 跳过非目标节点
不要逐个调用 Read() 遍历所有节点。应结合 NodeType 和 LocalName 精准定位目标元素,并用 ReadToFollowing("Item") 或 ReadToDescendant("Product") 快速跳转;对不需要的子树,用 Skip() 直接跳过整段,避免递归解析开销。
例如:只提取所有 <order></order> 下的 <id></id> 和 <amount></amount>,就无需进入 <customer></customer> 或 <shipping></shipping> 内部。
用 ReadElementContentAsXxx() 直接提取值
当确认当前节点是目标元素且内容为简单类型时,优先用强类型读取方法,比先 ReadElementString() 再转换更安全高效:
标签: node ai win stream c# 优化配置 .net
还木有评论哦,快来抢沙发吧~