在控制台项目中,我创建了一个 XDocument 并使用 linq 获取 xml 元素。请参阅以下代码。我尝试在可移植类库中使用它,但它不起作用。通过使用 linq to xml,控制台项目和可移植类库之间是否存在差异?
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
Stream strm = await response.Content.ReadAsStreamAsync();
XDocument doc = XDocument.Load(strm);
var de = from el in doc.Descendants("outline")
select new
{
title = (string)el.Element("title")
};
在下面的 xml 示例中:
<opml version="2.0">
<head>
<title>Outline of Category 41</title>
<dateCreated>Tue, 26 Nov 2013 10:15:02 +0100</dateCreated>
<docs>http://www.test.com</docs>
</head>
<body>
<outline title="Title1"/>
<outline title="Title2" />
</body>
</opml>
最佳答案
您正在寻找一个名为 title
的元素 - 但它实际上是一个属性。同样的代码在桌面上也会失败。你想要:
title = (string)el.Attribute("title")
不太清楚为什么你需要一个匿名类型——你可以使用:
var titles = doc.Descendants("outline")
.Select(x => (string) x.Attribute("title"));
(您可以使用查询表达式执行此操作,但我个人不会 - 查询表达式非常适合复杂查询,但当您只是过滤或投影时,它们添加的内容多于保存的内容。)
关于c# - 无法在可移植类库中使用 linq 查询找到 xml 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215917/