[英]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: 假设我有一个像这样的xml文件:
<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). 我想将其解析为C#动态代码,其中标记名称(名称,描述等)成为动态代码的属性(并包含标记内的数据)。
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. 然后我可以在其中进行查询.Where (i => i.id = 1)
中对IEnumerable<dynamic>
中的特定项目进行一些更改,然后更新XML文件。
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. XML文件不会太长,我只需要将其用作小型应用程序的数据库即可,在该应用程序中,不会连接到实际的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. 您可以将XML文件加载到XDocument中,将每个项目复制到ExpandoObject,对其进行操作,然后将项目复制回XDocument,然后保存到XML文件。
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 尝试以下链接: 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. 作为旁节点:Xml对动态不是很灵活。 What to do with namespaces for example? 例如,如何处理名称空间? Why not use XLinq? 为什么不使用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. 它需要更多的类型输入,但允许您保持灵活性,并避免动态类型输入,以我的直言,这不适合与XML结合使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.