开发者

What's a good way to parse an XML file into a C# IEnumerable<dynamic>?

Let's say I had an xml file like this:

<items>
 <item开发者_运维问答>
    <id>1</id>
    <name>Item 1</name>
    <description>This is item 1</description>
    <quantityLeft>10</quantityLeft>
  </item>
... (more items)
</items>

I'd like to parse it into a C# dynamic, where the tag names (name, description, etc...) become the property on the dynamic (and contains the data within the tags).

Where I could then do a query .Where (i => i.id = 1) for specific items in the IEnumerable<dynamic>, make some changes, and then update the XML file.

The XML file won't be too long, I just need it to act as a DB for a tiny app, where there will be no connectivity to an actual RDBMS.


You could load the XML file into an XDocument, copy each item to an ExpandoObject, manipulate that, copy the items back to an XDocument, and save to an XML file.

Load:

List<dynamic> items = XDocument
    .Load("input.xml")
    .Element("items")
    .Elements("item")
    .Select(item =>
    {
        IDictionary<string, object> dict = new ExpandoObject();
        foreach (var element in item.Elements())
            dict[element.Name.LocalName] = (string)element;
        return (dynamic)dict;
    })
    .ToList();

Manipulate:

var query = from item in items 
            where item.id == "1"
            select item;

foreach (var item in query)
{
    item.name = "New Name";
}

Save:

var doc = new XDocument(new XElement("items", items.Select(item =>
{
    IDictionary<string, object> dict = item as ExpandoObject;
    return new XElement("item", from kvp in dict
                                select new XElement(kvp.Key, kvp.Value));
})));

doc.Save("output.xml");

I'm sure there are much better options though.


Try the following link: http://blogs.msdn.com/b/mcsuksoldev/archive/2010/02/04/dynamic-xml-reader-with-c-and-net-4-0.aspx

As a sidenode: Xml to dynamic isnt very flexible. What to do with namespaces for example? Why not use XLinq? It requires a little more typing but allows you to keep beeing flexible and avoids dynamic typing which in my honest oppinion is no good candidate in conjuction with XML.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜