0

I know everyone says the best way to parse XML in C# is to use the XmlDocument class and do something like:

XmlNodeList list = xmlDoc.getElementsByTagName('tag');

However, I LOVE the way JavaScript encapsulates its XML and JSON, where every level of encapsulation within the XML or JSON document can be accessed using '.' i.e.:

test.xml

<item>
 <title>Title</title>
 <desc>
    <meta>MetaData</meta>
    <content>Ipsum Lorem</content>
 </desc>
 <date>1/1/2013</date>
</item>

In javasript I could parse this XML file and assign it to an object, var obj. I could then do something like:

obj.item[0].title ( 'Title' )
obj.item[0].desc.meta ('MetaData')

Is there any C# library that can parse the XML into something like this or do I have to do it the other way?

2
  • 1
    There isn't such a library because C# is compiled and JS is interpreted. You could create classes into which you could deserialize your XML if it's static. There's a tool to generate such classes from XML. Or you can use XDocument - a bit more verbose than custom class but better than XmlDocument Commented Feb 13, 2013 at 18:35
  • I know that "everybody" doesn't say use XmlDocument. I personally say use XDocument and LINQ to XML. Commented Feb 13, 2013 at 18:47

3 Answers 3

1

Not exactly the same, but this kind of approach (reading XML into a dynamic object) is similar in spirit:

http://www.codeproject.com/Articles/436406/Power-of-Dynamic-Reading-XML-and-CSV-files-made-ea

Sign up to request clarification or add additional context in comments.

1 Comment

this looks pretty damn close. Thanks I will give it a try
0

You might also want to take a look at a tool that should have been included with your visual studio installation: xsd.exe. Specifically take a look at the /classes switch. It isn't quite what you are looking for, but it will yield a similar syntax.

Comments

0

If you want to branch into the dynamic aspects of C# and ExpandoObject, there is a very clever library by @amazedsaint that seems like what you're after:

Example:

dynamic item = new ElasticObject("item");
item.Title = "Title";
item.Desc = new { Meta = "Metadata", Content="Lorem Ipsum" };
XElement asXml = item > FormatType.Xml;

// and from xml:
dynamic itemFromXml = asXml.ToElastic();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.