解析原始字符串的对象列表

2022-01-30 06:59:12 标签 c#sitecore

我在一个原始字符串值的链接列表有一种方法来解析原始字符串到一个对象的列表?

如:原始值:& lt; links> & lt;链接id = " {xxxxx-xxx-xxx} " linkid = =“xxxxx-xxx-xxx”文本“访问”linktype =“内部”目标=“空白”title =“访问”属性= " " linktext =“访问”/祝辞& lt;链接id = " {xxxx-xxx-xxx} " linkid = =“xxxx-xxx-xxx”文本“应用”linktype =“内部”目标=“空白”title =“应用”属性= " " linktext = "应用" /祝辞& lt; / links>

public IEnumerable<Link> Links {get;set;}

# # #试试这个

var xml=@"<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>";
......
using System.Xml.Serialization;
    
    var serializer = new XmlSerializer(typeof(Links));
    
    Links links;
    using (StringReader reader = new StringReader(xml))
    {
        links = (Links)serializer.Deserialize(reader);
        
    }
    
foreach (var link in links.Link)
    {
        Console.WriteLine($"Id: {link.Id} Text: {link.Text} ");
    }
}

输出

Id: {xxxxx-xxx-xxx} Text: Visit 
Id: {xxxx-xxx-xxx} Text: Apply 

[XmlRoot(ElementName = "link")]
public class Link
{
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
    [XmlAttribute(AttributeName = "linkid")]
    public string Linkid { get; set; }
    [XmlAttribute(AttributeName = "text")]
    public string Text { get; set; }
    [XmlAttribute(AttributeName = "linktype")]
    public string Linktype { get; set; }
    [XmlAttribute(AttributeName = "target")]
    public string Target { get; set; }
    [XmlAttribute(AttributeName = "title")]
    public string Title { get; set; }
    [XmlAttribute(AttributeName = "querystring")]
    public string Querystring { get; set; }
    [XmlAttribute(AttributeName = "linktext")]
    public string Linktext { get; set; }
}
[XmlRoot(ElementName = "links")]
public class Links
{
    [XmlElement(ElementName = "link")]
    public List<Link> Link { get; set; }
}
阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码