我不想使用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解析器。这是非常值得的! –