使用 C# 和 XML(XDocument) 的“:”中出现错误
本文关键字:错误 XML XDocument 使用 | 更新日期: 2023-09-27 18:32:32
我正在尝试一些东西,但在C#上使用xml XDocument时遇到了问题,但想不出有效的解决方法。
private void fillItems(string URL)
{
var webClient = new WebClient();
string result = webClient.DownloadString(URL);
XDocument reader = XDocument.Parse(result);
items.Clear();
foreach (var item in reader.Descendants("item"))
{
xmlItem temp = new xmlItem(item.Element("title").Value, (item.Element("torrent:magnetURI") != null ? item.Element("torrent:magnetURI").Value:"(no uri)"));
items.Add(temp);
}
updateList();
}
"torrent:magnetURI"给出了一个问题,指出不允许使用":"(在运行时),我无法取消完整结果字符串中的":",因为某些数据丢失了......
任何建议都非常感谢正在使用的输入 URL 是"http://kickass.so/anime/?rss=1"
torrent:
是一个命名空间。查询数据时必须使用命名空间:
var torrent = XNamespace.Get("YourNamespaceUrl");
foreach (var item in reader.Descendants("item"))
{
xmlItem temp = new xmlItem(item.Element("title").Value,
(item.Element(torrent + "magnetURI") != null
? item.Element(torrent + "magnetURI").Value
: "(no uri)"));
items.Add(temp);
}
此外,您可以将条件语句替换为??
和(string)XElement
大小写:
xmlItem temp = new xmlItem(item.Element("title").Value,
((string)item.Element(torrent + "magnetURI") ?? "(no uri)"));
如果你喜欢它的编码方式,我有一个使用该语法的公共 XML 库。但它也使它更简单,因为如果元素不存在,它就会采用默认值。
foreach (var item in reader.Descendants("item"))
{
xmlItem temp = new xmlItem(item.Element("title").Value,
item.Get("torrent:magnetURI", "(no uri)"));
items.Add(temp);
}
它通过内部使用以下命令为您确定torrent
命名空间:
XNamespace torrent = item.GetNamespaceOfPrefix("torrent");