我有一個很大的XML文件,我必須使用XmlReader讀取它,因爲它無法加載到內存中。該XML以這種方式(是一個簡化版本)格式:XmlReader如何讀取或跳過並不總是存在的特定子項
<?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>
孩子的(<Barcode><Code>
)是一種僅在一些產品,然後我不能跳在下一個「代碼」與最後ReadToFollowing
,因爲如果不存在我捕獲第一<product><code>
。
我不能控制XML輸出並且不能修改它(是第三方)。
有一種方法可以「」,這樣我可以具體應該尋找什麼,如果沒有找到我可以跳它?
謝謝你的幫助,請原諒我的壞英語。
嗨馬丁,謝謝你的建議。今天我會試着讓你知道。 –
嗨,馬丁,你建議我用XmlReader和XNode讀取每個Product的數據。一切運作良好,使用小內存,謝謝! –