我目前正在尝试通过将字节数组转换为XML字符串并在其上加载DOM来解析该字节数组。我的代码如下:
public static List<Purchase> ParsePurchases(Profile profile, byte[] data)
{
// Parse the profile XML and extract purchases
// read the data into a string
var xmlString = System.Text.Encoding.UTF8.GetString(data);
// create the DOM over it
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
// parse it
var purchaseElements = doc.GetElementsByTagName("purchase");
List<Purchase> purchases = new List<Purchase>();
for(var e = 0; e < purchaseElements.Count; e++)
{
var ele = (XmlElement)purchaseElements[e];
try
{
purchases.Add(
new Purchase(
profile,
Int32.Parse(ele.GetAttribute("id")),
Int32.Parse(((XmlElement)ele.GetElementsByTagName("price")[0]).InnerText),
Int32.Parse(((XmlElement)ele.GetElementsByTagName("quantity")[0]).InnerText),
((XmlElement)ele.GetElementsByTagName("description")[0]).InnerText
));
}
catch
{
throw new ArgumentException("Var ele is null");
}
}
return purchases;
}
我遇到的问题是此代码引发错误:
“根级别的数据无效,第1行,位置1”。
这是示例XML文档
<?xml version="1.0"?>
<profile username="215">
<purchases>
<purchase id="6271">
<price>728</price>
<quantity>14</quantity>
<description>Sample</description>
</purchase>
</purchases>
</profile>