dvReadSitemap function
The links in xml, a sitemap <urlset>, in file order. siteUrl, when
given, decides which links are this site's (shown as paths) and which leave
it; without it every absolute link is read as this site's.
Implementation
List<DVSitemapLink> dvReadSitemap(String xml, {String? siteUrl}) {
final XmlDocument document;
try {
document = XmlDocument.parse(xml);
} on Object {
return const <DVSitemapLink>[];
}
final XmlElement root = document.rootElement;
if (root.name.local != 'urlset') return const <DVSitemapLink>[];
final Uri? site = siteUrl == null ? null : Uri.tryParse(siteUrl);
final List<DVSitemapLink> links = <DVSitemapLink>[];
for (final XmlElement url in root.childElements.where((XmlElement element) => element.name.local == 'url')) {
final String loc = _child(url, 'loc')?.trim() ?? '';
if (loc.isEmpty) continue;
final Uri? address = Uri.tryParse(loc);
final bool external = site != null && address != null && address.hasAuthority && address.host != site.host;
final String path = external || address == null || !address.hasAuthority
? loc
: (address.path.isEmpty ? '/' : address.path) + (address.hasQuery ? '?${address.query}' : '');
final String? lastmod = _child(url, 'lastmod')?.trim();
links.add(DVSitemapLink(
url: loc,
path: path,
lastModified: lastmod == null || lastmod.isEmpty ? null : _date(lastmod),
external: external,
));
}
return links;
}