Swift:使用CheatyXML遍历XML并获取艺术家属性的技术问题
用CheatyXML解析Subsonic XML并映射到Artist对象
我帮你梳理下如何用CheatyXML遍历你提供的Subsonic响应XML,把艺术家的属性提取到你的Artist对象里~
首先先把你的示例XML贴出来方便参考:
<subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.16.0"> <indexes lastModified="1524417436798" ignoredArticles="The El La Los Las Le Les"> <index name="E"> <artist id="14" name="Editors"/> </index> <index name="K"> <artist id="27" name="Kings Of Leon"/> </index> </indexes> </subsonic-response>
步骤说明与代码示例
1. 先定义你的Artist对象(假设是C#环境,CheatyXML常用于.NET项目)
public class Artist { public int Id { get; set; } public string Name { get; set; } }
2. 核心解析代码
关键点是处理XML的默认命名空间,因为你的XML里指定了xmlns="http://subsonic.org/restapi",CheatyXML必须带上命名空间才能正确定位节点:
// 你的XML内容(可以从文件、API响应等方式获取) var xmlContent = @"<subsonic-response xmlns=""http://subsonic.org/restapi"" status=""ok"" version=""1.16.0""> <indexes lastModified=""1524417436798"" ignoredArticles=""The El La Los Las Le Les""> <index name=""E""> <artist id=""14"" name=""Editors""/> </index> <index name=""K""> <artist id=""27"" name=""Kings Of Leon""/> </index> </indexes> </subsonic-response>"; // 解析XML并初始化命名空间 var xml = CheatyXML.Parse(xmlContent); var subsonicNs = xml.Namespace("http://subsonic.org/restapi"); // 用于存储解析后的Artist对象 var artistList = new List<Artist>(); // 遍历所有<index>节点下的<artist> foreach (var indexNode in xml.SelectNodes(subsonicNs + "indexes/" + subsonicNs + "index")) { // 获取当前index下的artist节点 var artistNode = indexNode.SelectSingleNode(subsonicNs + "artist"); if (artistNode == null) continue; // 提取属性并映射到Artist对象 var artist = new Artist { Id = int.Parse(artistNode.Attribute("id").Value), Name = artistNode.Attribute("name").Value }; artistList.Add(artist); } // 测试输出结果 foreach (var artist in artistList) { Console.WriteLine($"艺术家ID: {artist.Id}, 名称: {artist.Name}"); }
重要注意事项
- 命名空间不能忽略:如果跳过命名空间,CheatyXML会找不到对应的节点,这是XML解析里很容易踩的坑。
- 属性类型转换:
id属性是字符串格式的数字,需要手动转换为int类型(如果你的Artist对象Id是数字类型的话)。 - 空节点判断:加上
if (artistNode == null) continue可以避免因为某个index下没有artist节点导致的空引用异常。
内容的提问来源于stack exchange,提问作者Alec.
相关产品推荐
相关产品推荐

