I am trying to retrieve data from an xml document to an array in C# using LINQ where I have to use some nested querying within the elements of the xml data which is as follows
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Catalog>
<Book ISBN="1.1.1.1" Genre="Thriller">
<Title Side="1">
<Pty R="1" ID="Seller_ID">
<Sub Typ="26" ID="John">
</Sub>
</Pty>
<Pty R="2" ID="ABC">
</Pty>
</Title>
</Book>
<Book ISBN="1.2.1.1" Genre="Thriller">
<Title Side="2">
<Pty R="1" ID="Buyer_ID">
<Sub Typ="26" ID="Brook">
</Sub>
</Pty>
<Pty R="2" ID="XYZ">
</Pty>
</Title>
</Book>
</Catalog>
In the above XML document Side="1" represents a sell side and Side="2" represents a sell side.
Now, I want to store above elements and attributes in an array which as fields as follows
Array ISBN Genre PublishDate Buyer_Company Seller_Company Buyer_Broker Seller_Broker
I was able to retrieve normal elements and attributes but was not sure how to deal with attributes that are dependent on other elements like
Buyer_Company
Seller_Company
Buyer_Broker
Seller_Broker
which are based on Side, Pty and Sub elements like Buyer_Company is ID attribute of Pty where R= 2 and Side=2. Similarly, Buyer_Broker is ID attribute of Sub element where its attribute Typ=26 (there can be XML data with different value of Typ) and Sub element is already a child to Pty element with R=1 and which is in turn a child of Book element when Side=2
Code I used to retrieve independent elements is
var result = doc.Descendants("Book")
.Select(b => new
{
ISBN= b.Attribute("ISBN").Value,
Genre=b.Attribute("Genre").Value,
PublishDate= b.Element("Title").Attribute("MMY").Value,
})
.ToArray();
And I worked on querying within a single element as follows
Company= (string)b.Descendants("Pty")
.Where(e => (int)e.Attribute("R") == 7)
.Select(e => e.Attribute("ID"))
.Single()
But this didn't consider the attribute Side in the element Book.
Sample Data
First Book Element
ISBN:1.1.1.1
Genre:Thriller
Seller_Company:NULL
Seller_Broker:NULL
Buyer_Company:ABC
Buyer_Broker:John
Second Book Element
ISBN:1.1.1.1
Genre:Thriller
Seller_Company:XYZ
Seller_Broker:Brook
Buyer_Company: NULL
Buyer_Broker:NULL
Side=1 represent a seller side and side=2 represents a buyer side which is why seller side is null in the first element of resultant array and buyer side in second element
May I know a better way to solve this?
