gpt4 book ai didi

asp.net - 使用 C# 将字典转换为 XML

转载 作者:行者123 更新时间:2023-12-02 08:50:10 24 4
gpt4 key购买 nike

我的 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。谁能建议我该怎么做?

最佳答案

反之亦然:

var result = new XDocument(new XElement("states",
dictionary.Select(i => new XElement("state", new XAttribute("name", i.Key),
i.Value.Select(v => new XElement("Location", new XAttribute("Name", v.Key),
new XElement("Address", v.Value.address),
new XElement("DateNTime", v.Value.datetime)
))
))
));

var xml = result.ToString();

这让你(通过使用你的数据片段):

<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>

关于asp.net - 使用 C# 将字典转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9037187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com