-3

I want to read <author> in <incollection> attribute. Elements have a same name but different in quantity.

How can I read authors from <incollection>? Please help to read first <incollection> there are three authors and second <incollection> have six authors.

<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>
Grant Winney
  • 65,241
  • 13
  • 115
  • 165

2 Answers2

1

In 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);

Prints a list of all authors from both incollections.

But if you want to filter it by key, your query would be something like this:

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);

This will print the list of authors in the second incollection

mnsr
  • 12,337
  • 4
  • 53
  • 79
  • Side notes - probably it's better to check exact match when you are filtering by key `(string)w.Attrinute("key") == keyValue`. Also its better to choose lamda variable name which correlates with object it represents - i.e. `i` for `incollection` and `a` for `author` – Sergey Berezovskiy May 15 '14 at 06:24
0

Have you considered Linq to XML?

You should be able to load your document and then query properties in CRUD manner.

Consider this question

LINQ to read XML

That will help you load your XML and then iterate through it and capture the properties you wish to capture.

Community
  • 1
  • 1
Matt
  • 25,943
  • 66
  • 198
  • 303