【发布时间】:2016-09-23 09:27:53
【问题描述】:
我有一个很大的 XML 文件,我必须使用 XmlReader 读取它,因为它无法加载到内存中。此 XML 以这种方式格式化(是缩减版):
<?xml version="1.0" encoding="windows-1252"?>
<Products>
<Product>
<Code>A14</Code>
<Name>Name1</Name>
<Manufacturer>
<Name>ManufacturerName</Name>
</Manufacturer>
<ProdCategories>
<ProdCategory>
<Code>015</Code>
<Name>ProdCategoryName</Name>
</ProdCategory>
</ProdCategories>
<Barcodes> <!-- note this line -->
</Barcodes>
</Product>
<Product>
<Code>A15</Code>
<Name>Name2</Name>
<Manufacturer>
<Name>ManufacturerName</Name>
</Manufacturer>
<ProdCategories>
<ProdCategory>
<Code>016</Code>
<Name>ProdCategoryName</Name>
</ProdCategory>
</ProdCategories>
<Barcodes>
<Barcode>
<Code>1234567890</Code> <!-- note this line -->
</Brcode>
</Barcodes>
</Product>
注意<Barcode> <Code> 元素:第一个<product> 缺失。
这是我用来读取它并将这些数据放入数据库的代码:
XmlReader reader = XmlReader.Create("Products.xml");
reader.MoveToContent();
do
{
reader.ReadToFollowing("Code");
code = reader.ReadElementContentAsString();
reader.ReadToFollowing("Name");
Name = reader.ReadElementContentAsString();
reader.ReadToFollowing("Name");
ManufacturerName = reader.ReadElementContentAsString();
reader.ReadToFollowing("Code");
ProdCategoryCode = reader.ReadElementContentAsString();
reader.ReadToFollowing("Code");
BarcodeCode = reader.ReadElementContentAsString();
//Here I use "code", "Name", "ManufacturerName" variables to insert into a database
} while (reader.Read());
reader.Close();
所有 XML 标记都存在于所有产品中,除了仅存在于某些产品上的 <Barcodes> childs (<Barcode><Code>),那么我无法使用最后一个 ReadToFollowing 跳转到下一个“代码”,因为如果不存在我会捕获第一个<product><code>。
我无法控制 XML 输出,也无法修改它(是第三方)。
有一种方法可以“ReadToFollowing('<Barcodes><Barcode><Code>')”,这样我就可以明确应该寻找什么,如果没有找到我可以跳过它吗?
谢谢你的帮助,原谅我的英语不好。
【问题讨论】: