我不想使用XMLDocument,因爲我使用XMLWriter編寫了XML編寫代碼。所以應該沒有理由改變。C#XMLReader不能正確解析
<Player>
<Friends />
<Ignores>
<Ignore>117779</Ignore>
<Ignore>44237636758361374</Ignore>
<Ignore>564534831</Ignore>
</Ignores>
<InventoryItems>
<Item>
<Slot>0</Slot>
<Id>995</Id>
<Amount>39493</Amount>
</Item>
<Item>
<Slot>27</Slot>
<Id>1049</Id>
<Amount>12</Amount>
</Item>
</InventoryItems>
<BankItems />
</Player>
我試圖解析那裏。這是我到目前爲止。似乎到處打破我有它與<Ignore>'s
工作了一點點,但那是當我使用ReadToFollowing
而不是ReadToNextSibling
,它會工作,直到ReadToFollowing擊中一個空行..它只會打到EOF。
XmlTextReader reader = new XmlTextReader(misc.getServerPath() + "\\accounts\\" + username + ".xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "Friends") {
if (!reader.IsEmptyElement) //got any friends
{
while (reader.ReadToFollowing("Friend"))
//do_stuff_with_that_data(reader.ReadElementContentAsLong());
}
} else if (reader.NodeType == XmlNodeType.Element && reader.Name == "Ignores") {
if (!reader.IsEmptyElement) //got any ignores
{
reader.ReadToFollowing("Ignore");
while (reader.ReadToNextSibling("Ignore"))
{
//do_stuff_with_that_data(reader.ReadElementContentAsLong());
}
}
} else if (reader.NodeType == XmlNodeType.Element && reader.Name == "InventoryItems") {
if (!reader.IsEmptyElement) //got items
{
int slot, id, amount;
while (reader.ReadToNextSibling("Item"))
{
reader.ReadToFollowing("Slot");
slot = reader.ReadElementContentAsInt();
reader.ReadToFollowing("Id");
id = reader.ReadElementContentAsInt();
reader.ReadToFollowing("Amount");
amount = reader.ReadElementContentAsInt();
//do_stuff_with_that_data(slot, id, amount);
}
}
} else if (reader.NodeType == XmlNodeType.Element && reader.Name == "BankItems") {
if (!reader.IsEmptyElement) //got bank items
{
int slot, id, amount;
while (reader.ReadToNextSibling("Item"))
{
reader.ReadToFollowing("Slot");
slot = reader.ReadElementContentAsInt();
reader.ReadToFollowing("Id");
id = reader.ReadElementContentAsInt();
reader.ReadToFollowing("Amount");
amount = reader.ReadElementContentAsInt();
//do_stuff_with_that_data(slot, id, amount);
}
}
}
如果您需要最高性能或者文檔太大而無法放入RAM,XmlReader是非常棒的。對於我推薦使用LINQ to XML的其他東西 - 我已經能夠用更簡潔的<50行LINQ to XML查詢替換> 200行XmlReader解析器。這是非常值得的! –