我希望每个<div class="person"> { /*JSON stuff/* }
对象都成为对象列表中的单独元素。它与其他html content(...html tags...
)混合在一起。我有一个来自html文件的字符串:
...html tags...
<div class="person">
{
"name":"Bob",
"age":20,
"color":"blue"
}
</div>
...html tags...
<div class="person">
{
"name":"John",
"age":30,
"color":"green"
}
</div>
...html tags...
无法预测会有多少人。我认为我将使用Regex,Json或Substring。我的问题是这些人周围还有许多其他内容,我不知道将每个元素作为对象列表中的单独元素的最简单解决方案是什么。
例如,我有一个像这样的类:
class Person
{
public string name {get;set;}
public int age {get;set;}
}
我想List<Person>
从此html上传列表。
看看是否有帮助...
using System;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
namespace ConsoleApp1 {
class Program {
static void Main(string[] args) {
// Just get your input loaded into a variable called input
var input = @"
<div class='person'>
{
'name':'Bob',
'age':20,
'color':'blue'
}
</div>
<div class='dog'>
{
'name':'Jim',
'age':30,
'color':'green'
}
</div>
<div class='person'>
{
'name':'John',
'age':30,
'color':'green'
}
</div>
".Replace("'", "\"");
Regex personContents = new Regex("<div class=\"person\">(.+?)</div>", RegexOptions.Singleline);
var persons = personContents.Matches(input).Cast<Match>().Take(6).Select(x => JsonConvert.DeserializeObject<Person>(x.Groups[1].Value.Trim())).ToArray();
var names = string.Join(",", persons.Select(x => x.name));
Console.WriteLine($"names={names}");
}
class Person {
public string name { get; set; }
public int age { get; set; }
//public string color { get; set; }
}
}
}
上面的代码显示“ Bob,John”。这不能解决过滤出重复项的问题,但是使用LINQ的Distinct()方法仅捕获唯一记录就足够容易了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句