我需要输出如下,我该怎么做?
name1
title1
title2
name2
title1
title2
在那个for循环中我必须显示标题。这里我使用了下面的代码,这意味着我收到以下错误:
'char' does not contain a definition for 'Attribute' and no extension method 'Attribute' accepting a first argument of type 'char' could be found (are you missing a using directive or an assembly reference
如何解决上述错误?如何在for循环中编写条件以显示标题?
我使用过这段代码:
XmlSerializer serializer = new XmlSerializer(typeof(Notchs));
XDocument xmlDoc = XDocument.Parse(dataInXmlFile);
var Categories = (from Category in xmlDoc.Descendants("Category")
select new Notch()
{
name = (string)Category.Attribute("name"),
title = Category.Elements("Articles").Elements("article").ToString()
}).ToList();
foreach(var doc in Categories)
{
foreach(var sec in doc.title)
{
sec.Attribute("title").Value.ToList(),
}
}
NotchsList.ItemsSource = Categories.ToList();
XML
<Categories>
<Category name="notchbolly">
<Articles>
<article articleid="170" title="Colour And Vibrancy Are Part Of Our DNA">...</ article>
<article articleid="187" title="German chef gets saucy!!">...</article>
<article articleid="2004" title="Meet-the-Face-of-Compassion">...</article>
<article articleid="2005" title="Dutt’s-family-gets-together!">...</article>
<article articleid="1933" title="NOTCH easy to do recipe- Mushroom Risotto with truffles">...</article>
<article articleid="1934" title="NOTCH easy to do recipe- Lobster with Black ink Linguini Arabiatta">...</article>
<article articleid="1935" title="Yash Birla- 100% Living">...</article>
</Articles>
</Category>
<Category name="notchfashion">
<Articles>
<article articleid="81" title="Making Headlines">...</article>
<article articleid="99" title="Ladakh through my Lens">...</article>
<article articleid="689" title="A-Family-Affair">...</article>
<article articleid="2264" title="Sushmita-back-with-Manav?">...</article>
<article articleid="70" title="NOTCH- Making of the cover- Farhan Akhtar & Javed Akhtar">...</article>
<article articleid="78" title="NOTCH easy to do recipe- Aubergine Carpaccio">... </article>
<article articleid="1935" title="Yash Birla- 100% Living">...</article>
</Articles>
</Category>
答案 0 :(得分:5)
在您的代码title
中,属性是字符串,而不是字符串列表。因此,在内部foreach中,您试图通过char枚举字符串char。你也想从循环中获取char
的属性。当然,char
不是XElement
,它没有Attribute
方法。
使用字符串列表(并使用PascalCase名称作为属性)。
// why are you named class Notch? use Category!
public class Notch
{
public string Name { get; set; }
public List<string> Titles { get; set; }
}
类似的东西(没有看到你的xml就无法确定):
XDocument xmlDoc = XDocument.Parse(dataInXmlFile);
var Categories =
(from Category in xmlDoc.Descendants("Category")
select new Notch()
{
Name = (string)Category.Attribute("name"),
Titles = Category.Element("Articles").Elements("article")
.Select(a => (string)a.Attribute("title")).ToList()
}).ToList();
foreach(var category in Categories)
{
foreach(var title in category.Titles)
{
// use title
}
}
NotchsList.ItemsSource = Categories.ToList();
还有一个建议 - 为短范围变量使用短名称(比如Linq查询中的范围变量)。因此,例如上面,您可以使用简单的Category
。
c
变量
更新请记住,您的xml中有未转义的&符号。带有&
的&符号should be escaped。