【发布时间】:2016-06-17 20:38:12
【问题描述】:
我有以下转换为字符串的 xml 文件 我想解析 xml 文件,只返回带有文件扩展名的 url
<?xml version="1.0" encoding="utf-8"?>
<channel>
<generator>GOA Celebrations</generator>
<generator>GOA Celebrations</generator>
<pubDate>13 Jan 2016</pubDate>
<title>GOA Celebrations</title>
<link>http://goframe.com.au/rss/herston-inbound</link>
<language>en</language>
<image>
<url>http://goafame.com.au/site/templates/img/logo.png</url>
</image>
<item>
<title>Herston Inbound - Wednesday, 13 Jan - Alex Peisker - 2015-12-21 09:26am - Live</title>
<description></description>
<pubDate>13 Jan 2016 10:32:01 AEST</pubDate>
<link>http://goafame.com.au/gallery/entry/2991/</link>
<enclosure url="http://goafame.com.au/site/assets/files/2991/final_cropped_shutterstock_114908098.jpg" length="" type="" />
<guid isPermaLink="false">c5c1cb0bebd56ae38817b251ad72bedb</guid>
</item>
<item>
<title>Dog 1</title>
<description></description>
<pubDate>13 Jan 2016 10:32:01 AEST</pubDate>
<link>http://goafame.com.au/gallery/entry/2991/</link>
<enclosure url="http://animaliaz-life.com/data_images/dog/dog4.jpg" length="" type="" />
</item>
<item>
<title>Dog 2</title>
<description></description>
<pubDate>13 Jan 2016 10:32:01 AEST</pubDate>
<link>http://goafame.com.au/gallery/entry/2991/</link>
<enclosure url="http://cdn1.theodysseyonline.com/files/2015/12/21/6358631429926013411708851658_Dog-Pictures.jpg" length="" type="" />
</item>
<item>
<title>Dog 3</title>
<description></description>
<pubDate>13 Jan 2016 10:32:01 AEST</pubDate>
<link>http://goafame.com.au/gallery/entry/2991/</link>
<enclosure url="https://i.ytimg.com/vi/AkcfB3z0_-0/maxresdefault.jpg" length="" type="" />
</item>
</channel>
我的问题是如何使用
正则表达式
期望的输出是
http://goafame.com.au/site/templates/img/logo.png http://goafame.com.au/site/assets/files/2991/final_cropped_shutterstock_114908098.jpg http://animaliaz-life.com/data_images/dog/dog4.jpg http://cdn1.theodysseyonline.com/files/2015/12/21/6358631429926013411708851658_Dog-Pictures.jpg
这是我到目前为止所尝试的
Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string rawString = doc.ToString();
int posCounter = 0;
foreach (Match m in linkParser.Matches(rawString))
{
posCounter++;
links.Add(new LinkModel
{
IsSelected = false,
XmlLink = m.Value,
NodePosition = posCounter
});
}
注意: XML 文件可以来自任何来源,并且其他一些 url 不位于链接元素中。有些甚至是嵌套的。这就是我考虑使用 RegEx 而不是 XDocument 的原因。
【问题讨论】:
-
为什么需要正则表达式?使用 Xpath 只需一行代码:)
-
不要为此使用 RegEx。只需使用 XML 解析器。以 XDocument 为例。
-
恕我直言,使用正则表达式解析 XML 不是一个好主意。我会选择 DOM 或 SAX。
-
是否可以使用 XDocumet 获取 url(注意 XML 文件是动态的,有些 url 可能不是来自附件标签)?