使用 C# 将字典转换为 XML
我的 XML 文件如下:
<states>
<state name ="Alaska">
<Location Name="loc1">
<Address>testadd1</Address>
<DateNTime>d1</DateNTime>
</Location>
<Location Name="loc2">
<Address>add2</Address>
<DateNTime>d2</DateNTime>
</Location>
</state>
</states>
我已将其转换为以下字典,如下所示:
XDocument doc = XDocument.Load(Server.MapPath("test2.xml"));
IDictionary<string, Dictionary<string, Property>> dictionary = doc.Root.Elements("state").ToDictionary(
s => s.Attribute("name").Value,
s => s.Elements("Location").ToDictionary(
loc => loc.Attribute("Name").Value,
loc => new Property
{
address = loc.Element("Address").Value,
datetime = loc.Element("DateNTime").Value
}));
class :
public class Property
{
public string address;
public string datetime;
}
我已对字典进行了更改,现在我需要将其转换回 XML 。谁能建议我该怎么做?
I have my XML File as follows:
<states>
<state name ="Alaska">
<Location Name="loc1">
<Address>testadd1</Address>
<DateNTime>d1</DateNTime>
</Location>
<Location Name="loc2">
<Address>add2</Address>
<DateNTime>d2</DateNTime>
</Location>
</state>
</states>
I have converted this to the following dictionary as follows:
XDocument doc = XDocument.Load(Server.MapPath("test2.xml"));
IDictionary<string, Dictionary<string, Property>> dictionary = doc.Root.Elements("state").ToDictionary(
s => s.Attribute("name").Value,
s => s.Elements("Location").ToDictionary(
loc => loc.Attribute("Name").Value,
loc => new Property
{
address = loc.Element("Address").Value,
datetime = loc.Element("DateNTime").Value
}));
class :
public class Property
{
public string address;
public string datetime;
}
I have made changes to my dictionary, Now I need to convert this back to XML . Can anyone suggest me how I could go about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以反之亦然:
这会让你(通过使用你的数据片段):
You could do it vise versa:
This gets you (by using your data fragment):
如果您不需要使用 IDictionary,我发现使用
XmlSerializer
非常容易。模型
从 XML 反序列化对象
将对象序列化为 XML
If you do not require using an IDictionary, I find it very easy to work with the
XmlSerializer
.Models
Deserializing objects from XML
Serializing objects to XML