因此,我尝试将以下XML文档反序列化为自定义类型(ItemModel)的多个对象。自从我为Windows 8平台开发以来,由于库不兼容,我已经遇到了大量的问题。我想要做的是将每个ItemModel反序列化为一个对象,而不是将它们添加到某种类型的List中。从我所拥有的,代码运行但列表没有填充。
<?xml version="1.0" encoding="utf-8" ?>
<Items>
<ItemModel>
<ID>0</ID>
<Name>Apple</Name>
<Category>Compost</Category>
<ImageWidth>67</ImageWidth>
<ImageHeight>100</ImageHeight>
<Description>An Apple is a compost item that....</Description>
<ImagePath>Graphics\\apple.png</ImagePath>
</ItemModel>
<ItemModel>
<ID>0</ID>
<Name>Water Bottle</Name>
<Category>Mixed Containers</Category>
<ImageWidth>67</ImageWidth>
<ImageHeight>100</ImageHeight>
<Description>A Water bottle is a mixed container item that...</Description>
<ImagePath>Graphics\\Bottle.png</ImagePath>
</ItemModel>
</Items>
注意:我在使用XmlReader时也遇到了一些问题。即使我使用XmlReader.Create()之后,读者也等于null。
谢谢。
答案 0 :(得分:0)
如果您正在读取.xml文件并在Web浏览器中显示并且您的代码是C#,那么您可以执行以下操作:
protected void Page_Load(object sender, EventArgs e)
{
ReadXmlFile(Server.MapPath("~/XMLFiles/Items.xml"));
}
private void ReadXmlFile(string fileName)
{
string parentElementName = "";
string childElementName = "";
string childElementValue = "";
bool element = false;
lblMsg.Text = "";
XmlTextReader xReader = new XmlTextReader(fileName);
while (xReader.Read())
{
if (xReader.NodeType == XmlNodeType.Element)
{
if (element)
{
parentElementName = parentElementName + childElementName + "<br>";
}
element = true;
childElementName = xReader.Name;
}
else if (xReader.NodeType == XmlNodeType.Text | xReader.NodeType == XmlNodeType.CDATA)
{
element = false;
childElementValue = xReader.Value;
lblMsg.Text = lblMsg.Text + "<b>" + parentElementName + "<br>" + childElementName + "</b><br>" + childElementValue;
parentElementName = "";
childElementName = "";
}
}
xReader.Close();
}
}