C# 如何读取xml文件中名称相同但数量不同的多个元素
我想在C# 如何读取xml文件中名称相同但数量不同的多个元素,c#,xml,C#,Xml,我想在属性中读取。元素名称相同,但数量不同 如何阅读中的作者?请帮忙阅读 第一个有三位作者,第二个有六位作者 <incollection mdate="2013-09-10" key="series/cogtech/HuangEV04"> <author>Zhisheng Huang</author> <author>Anton Elins</author> <author>Cees T. Visse
属性中读取
。元素名称相同,但数量不同
如何阅读
中的作者?请帮忙阅读
第一个
有三位作者,第二个
有六位作者
<incollection mdate="2013-09-10" key="series/cogtech/HuangEV04">
<author>Zhisheng Huang</author>
<author>Anton Elins</author>
<author>Cees T. Visser</author>
<title>STEP: a Scripting Language for Embodied Agents.</title>
<pages>87-110</pages>
<year>2004</year>
<booktitle>Life-like characters</booktitle>
<crossref>series/cogtech/354000867</crossref>
<url>db/series/cogtech/354000867.html#HuangEV04</url>
</incollection>
<incollection mdate="2013-09-10" key="series/cogtech/PaivaPMMVS04">
<author>Ana Paiva</author>
<author>Rui Prada</author>
<author>Isabel Machado</author>
<author>Carlos Martinho</author>
<author>Marco Vala</author>
<author>Andr Silva</author>
<title>Playing with Agents-Agents in Social and Dramatic Games.</title>
<pages>361-376</pages>
<year>2004</year>
<booktitle>Life-like characters</booktitle>
<crossref>series/cogtech/354000867</crossref>
<url>db/series/cogtech/354000867.html#PaivaPMMVS04</url>
</incollection>
黄志胜
安东·埃林斯
维瑟
步骤:一种用于嵌入式代理的脚本语言。
87-110
2004
栩栩如生的人物
系列/cogtech/354000867
db/series/cogtech/354000867.html#HuangEV04
安娜·帕瓦
鲁伊普拉达
伊莎贝尔·马查多
卡洛斯·马丁尼奥
马可瓦拉
安德尔席尔瓦
在社交和戏剧游戏中与经纪人一起玩。
361-376
2004
栩栩如生的人物
系列/cogtech/354000867
db/series/cogtech/354000867.html#paivapmvs04
您考虑过Linq到XML吗
您应该能够加载文档,然后以CRUD方式查询属性
考虑这个问题
这将帮助您加载XML,然后对其进行迭代,并捕获您希望捕获的属性。在LINQ to XML中:
var xd = XDocument.Load(@"C:\myXml.xml");
var authors = xd.Root
.Elements("incollection")
.Elements("author")
.Select (x => x.Value);
foreach (var x in authors)
Console.WriteLine (x);
打印两个目录中所有作者的列表
但是,如果您想按键过滤它,您的查询将如下所示:
var authorsFiltered = xd.Root
.Elements("incollection")
.Where (w => w.Attribute("key").Value.Contains("PaivaPMMVS04"))
.Elements("author")
.Select (x => x.Value);
foreach (var x in authorsFiltered)
Console.WriteLine (x);
这将在第二个附录中打印作者列表-当您按key
(string)w.Attrinute(“key”)==keyValue
进行筛选时,最好检查精确匹配。另外,最好选择与它所表示的对象相关的lamda变量名,即i
用于incollection
和a
用于author