Friday, 9 August 2013

Determining Parent Element XML C#

Determining Parent Element XML C#

I'm currently looping over an XML document. Structure shown below (data
changed)
<activity date="2013-07-05T06:42:37" name="view" host="00.000.00.000">
<user id="EU-user@user.co.uk" name="U user" memberType="E" />
<storageObject docId="0000-0000-0000" name="2. Extract Lease -
31.07.2003" size="1903885" fileExtension="pdf">
<cabinet name="Company Intranet">NG-FGW7XX1Y</cabinet>
<Matter>0000</Matter>
<Client>X01659</Client>
<Author>Joe Bloggs</Author>
</storageObject>
</activity>
What I need to do is loop over each activity element, and print the
information held in each child element and attribute. Currently I have
this
var root = doc.Root;
foreach (XElement el in root.Elements().DescendantsAndSelf())
{
if (el.Value.Equals(""))
{
//don't print anything, just move along, nothing to
see here
}
else
{
Console.WriteLine(el.Value);
}
//Console.WriteLine(" Attributes:");
if (el.HasAttributes == true)
{
foreach (XAttribute attr in el.Attributes())
{
Console.WriteLine(attr.ToString());
// Console.WriteLine(el.Elements("id"));
}
}
}
Which works to some extent, except that there is no obvious distinction as
to where the activity element ends (ie, it prints a wall of text once it's
finished, and I'd like to be able to distinguish between elements). It
also prints the cabinet element twice throughout, but as a concatenated
version of the child elements, before looping through and printing them
out individually. As shown below
NG-FGW7XX1Y0000X01659Joe Bloggs
date="2013-07-05T06:42:37"
name="view"
host="00.000.00.000"
id="EU-user@user.co.uk"
name="U user"
memberType="E"
NG-FGW7XX1Y0000X01659Joe Bloggs
docId="0000-0000-0000"
name="2. Extract Lease - 31.07.2003"
size="1903885"
fileExtension="pdf"
NG-FGW7XX1Y
name="Company Intranet"
0000
X01659
Joe Bloggs
I need to be able to loop over the individual activity element, and print
out all the elements and attributes without the concatenated lines. I'd
also like to be able to insert a Console.WriteLine("------"); so I can
easily see on the console where each activity ends. Any suggestions?
The reason I'm looping over elements is that some records have additional
elements that otherwise wouldn't be found.

No comments:

Post a Comment