I want to try and return an object from an XML reader that I wrote to process a file that will have a partially unknown structure.
Here is a sample of the XML.
<xml>
<strings>
<Home>
<Index>
<PreWrapper>
<Left>
<Title>Blah</Title>
<Body>Lorem ipsum dolor sit amet, consec tetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nonummy hendrerit mauris. Phasellus porta. Fusce suscipit</Body>
<LinkText>read more</LinkText>
<LinkUrl>#</LinkUrl>
</Left>
<Center>
<Title>Exploit your ideas</Title>
<Body>Lorem ipsum dolor sit amet, consec tetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nonummy hendrerit mauris. Phasellus porta. Fusce suscipit</Body>
<LinkText>read more</LinkText>
<LinkUrl>#</LinkUrl>
</Center>
<Right>
<Title>Grow your business</Title>
<Body>Lorem ipsum dolor sit amet, consec tetuer adipiscing elit. Praesent vestibulum molestie lacus. Aenean nonummy hendrerit mauris. Phasellus porta. Fusce suscipit</Body>
<LinkText>read more</LinkText>
<LinkUrl>#</LinkUrl>
</Right>
</PreWrapper>
</Index>
</Home>
</strings>
<config>
<Home>
<Index>
<ShowPreWrapper>True</ShowPreWrapper>
</Index>
</Home>
</config>
</xml>
I want to be able to just call with my reader
var left = reader.GetObject("xml/strings/Home/Index/PreWrapper/Left");
and I want it to return an anonymous object (or a dynamic object, but I don't know much about those) that looks like
left.Title
left.Body
left.LinkText
left.LinkUrl
or
var xml = reader.GetObjcet("xml");
and be able to dive right into it like
xml.strings.Home.Index....
but I just cannot figure out how to create this object. Is this even possible?
I think that you could approximate this using the ExpandoObject
class, but it is quite likely that there are better ways to do it (like using a more loosely typed language, using dictionaries, etc.)
There is certainly nothing built in to the .NET BCL to do this.
EDIT: I found this recently, and it probably applies in this situation: ElasticObject
.
You can't do this, since C# is a strong-typed language. Maybe it's possible somehow using dynamic C#, but I don't know much about it. But as a solution, you can parse your XML into dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With