如何将包含链接列表的原始字符串解析为Link类型对象列表
解析XML格式链接字符串为对象列表方案
你提供的原始字符串是标准XML格式,可通过以下两种.NET原生方法解析为IEnumerable<Link>对象列表:
方法1:Linq to XML(灵活轻量,无需序列化配置)
无需额外引入第三方包,仅需引用System.Xml.Linq命名空间即可快速实现:
- 首先定义Link实体类
public class Link { public string Id { get; set; } public string LinkId { get; set; } public string Text { get; set; } public string LinkType { get; set; } public string Target { get; set; } public string Title { get; set; } public string QueryString { get; set; } public string LinkText { get; set; } }
- 编写解析代码
using System.Xml.Linq; // 替换为你的原始XML字符串 string rawXml = @"<links><link id=""{xxxxx-xxx-xxx}"" linkid=""xxxxx-xxx-xxx"" text=""Visit"" linktype=""internal"" target=""blank"" title=""Visit"" querystring="""" linktext=""Visit"" /><link id=""{xxxx-xxx-xxx}"" linkid=""xxxx-xxx-xxx"" text=""Apply"" linktype=""internal"" target=""blank"" title=""Apply"" querystring="""" linktext=""Apply"" /></links>"; XDocument xDoc = XDocument.Parse(rawXml); IEnumerable<Link> Links = xDoc.Descendants("link") .Select(node => new Link { Id = node.Attribute("id")?.Value, LinkId = node.Attribute("linkid")?.Value, Text = node.Attribute("text")?.Value, LinkType = node.Attribute("linktype")?.Value, Target = node.Attribute("target")?.Value, Title = node.Attribute("title")?.Value, QueryString = node.Attribute("querystring")?.Value, LinkText = node.Attribute("linktext")?.Value });
方法2:XML反序列化(适合固定XML结构的场景)
通过XML序列化特性映射节点属性,适合结构固定的XML解析场景:
- 定义带序列化特性的实体类
using System.Xml.Serialization; // 对应根节点links [XmlRoot("links")] public class LinkRoot { [XmlElement("link")] public List<Link> LinkList { get; set; } } public class Link { [XmlAttribute("id")] public string Id { get; set; } [XmlAttribute("linkid")] public string LinkId { get; set; } [XmlAttribute("text")] public string Text { get; set; } [XmlAttribute("linktype")] public string LinkType { get; set; } [XmlAttribute("target")] public string Target { get; set; } [XmlAttribute("title")] public string Title { get; set; } [XmlAttribute("querystring")] public string QueryString { get; set; } [XmlAttribute("linktext")] public string LinkText { get; set; } }
- 编写反序列化代码
using System.IO; using System.Xml.Serialization; string rawXml = @"替换为你的原始XML字符串"; XmlSerializer serializer = new XmlSerializer(typeof(LinkRoot)); using (var reader = new StringReader(rawXml)) { LinkRoot root = (LinkRoot)serializer.Deserialize(reader); IEnumerable<Link> Links = root.LinkList; }
注意事项
- 两种方法均基于.NET基础类库实现,无需依赖第三方组件
- 代码中使用
?.Value可避免XML属性缺失时触发空引用异常 - 可根据业务需要调整Link类的属性类型,比如将Id属性转为Guid类型
内容的提问来源于stack exchange,提问作者GSKKC
相关产品推荐
相关产品推荐

