【发布时间】:2020-01-30 18:48:30
【问题描述】:
我有问题。 在我的 Xamarin Forms 应用程序中,我对我的网页进行网络调用,我在其中收集 XML 以在应用程序中使用。我将 XML 解析为 3 个不同的列表。
- 专辑
- 图片
- 格式
现在这是我的 xml 的样子:
<Data>
<Albums>
<Album>
<Image></Image>
<Image></Image>
<Image></Image>
</Album>
<Album>
<Image></Image>
<Image></Image>
</Album>
</Albums>
<Images>
<Image></Image>
<Image></Image>
<Image></Image>
<Image></Image>
</Images>
<Formats>
<Format></Format>
<Format></Format>
</Formats>
</Data>
解析后,想要的结果是:
lstAlbums.Count = 2
lstImages.Count = 4
lstFormats.Count = 2
但显然它会计算完整 xml 中的所有 <> 标签,因此 lstImages 的计数为 9,因为专辑中有 5 个,<Images> 中有 4 个
这是我的 C# 代码:
if (!string.IsNullOrEmpty(xmlString))
{
doc = XDocument.Parse(xmlString);
}
//Check if xml has any elements
if (!string.IsNullOrEmpty(xmlString) && doc.Root.Elements().Any())
{
App.lstAlbums = doc.Descendants("Albums").Descendants("Album").Select(d =>
new Album
{
Id = Convert.ToInt32(d.Element("Id").Value),
Name = d.Element("Name").Value,
Images = doc.Descendants("Album").Descendants("Image").Select(a =>
new myImage
{
Id = Convert.ToInt32(a.Element("Id").Value),
Name = a.Element("Name").Value,
Size = a.Element("Size").Value,
Price = Convert.ToDecimal(a.Element("Price").Value)
}).ToList(),
Prijs = Convert.ToDecimal(d.Element("Price").Value)
}).ToList();
App.lstImages = doc.Descendants("Images").Descendants("Image").Select(e =>
new myImage
{
Id = Convert.ToInt32(e.Element("Id").Value),
Name = e.Element("Name").Value
}).ToList();
App.lstFormats = doc.Descendants("Formats").Descendants("Format").Select(e =>
new Format
{
Id = Convert.ToInt32(e.Element("Id").Value),
Size = e.Element("Size").Value,
Price = Convert.ToDecimal(e.Element("Price").Value)
}).ToList();
}
我该如何解决这个问题?
【问题讨论】:
-
Descendents方法是递归的;如果您只打算查看一个级别,请改用Elements,但坦率地说,这看起来很适合XmlSerializer,而不是手动解析。 -
您能否为我的其中一个列表(例如专辑)提供示例代码?
-
我要反序列化这个,手动解析只是很多已经存在的代码。
标签: c# xml parsing xamarin.forms