我使用 XDocument.Load("Somelink") 获得 Rss 提要;我正在从服务器获取 XML 输出。
<item>
<title>Senior Web Developer</title>
<link>Some link</link>
<guid isPermaLink="false">Some link</guid>
<description><![CDATA[University of UK <br />Salary: £39,324 to £46,924 pa]]></description>
</item>
在描述标签中我得到了公司信息和薪水,我只需要该描述中的薪水部分,如何从该链接中提取薪水。
var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
description = x.Element("description").Value
});
如何从描述标签中提取工资。我想用两个不同的标签显示薪水。
我需要在 Grid View 中输出 Salary from 和 Salary to。我尝试了 Regex.Match 方法,它只给出前两位数字。
代码:-
<asp:GridView ID="gRss" runat="server" AutoGenerateColumns="false"
ShowHeader="false" CssClass="table table-bordered table-striped">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table class="table table-bordered table-striped">
<tr>
<td class="info"><%#Eval("Title") %></td>
</tr>
<tr>
<td><%#Eval("SalaryFrom") %></td>
</tr> <tr>
<td><%#Eval("SalaryTo") %></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C#代码
List<Feeds> feeds = new List<Feeds>();
try
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load("Some link");
var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
description = x.Element("description").Value
});
if(items != null)
{
foreach(var i in items)
{
// string resultString = Regex.Match(i.description, @"\d+").Value;
//resultString = Regex.Match(subjectString, @"\d+").Value;
var match = Regex.Match(i.description, @": £(?<from>.*?) to £(?<to>.*?) ");
var from = match["from"].Value;
var to = match["to"].Value;
Feeds f = new Feeds
{
Title = i.title,
Description = resultString
};
feeds.Add(f);
}
}
gRss.DataSource = feeds;
gRss.DataBind();
}
最佳答案
这个正则表达式 : £(?<from>.*?) to £(?<to>.*?)
使用命名捕获组 from
和 to
.在它的帮助下,从 description
中提取所需的值.
var match = Regex.Match(description, @": £(?<from>.*?) to £(?<to>.*?) ");
var from = match.Groups["from"].Value;
var to = match.Groups["to"].Value;
编辑:添加了.Groups
属性(property)。
关于c# - 使用 C# 从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479717/