使用 C# 将字典转换为 XML

发布于 2024-12-29 04:03:54 字数 1163 浏览 0 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

太阳男子 2025-01-05 04:03:54

你可以反之亦然:

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>

You could do it vise versa:

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();

This gets you (by using your data fragment):

<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>
笑,眼淚并存 2025-01-05 04:03:54

如果您不需要使用 IDictionary,我发现使用 XmlSerializer 非常容易。

模型

[XmlRoot(ElementName="states")]
public class Container
{
    [XmlElement("state")]
    public List<State> States { get; set; }
}

public class State
{
    [XmlAttribute()]
    public string name { get; set; }

    [XmlElement("Location")]
    public List<Location> Locations { get; set; }
}

public class Location
{
    [XmlAttribute()]
    public string Name { get; set; }

    public string Address { get; set; }

    public DateTime DateNTime { get; set; }
}

从 XML 反序列化对象

var xml = @"<?xml version='1.0' encoding='utf-16'?>
                    <states>
                     <state name ='Alaska'>
                      <Location Name='loc1'>
                       <Address>testadd1</Address>
                       <DateNTime>2012-01-01</DateNTime>
                      </Location>
                      <Location Name='loc2'>
                       <Address>add2</Address>
                       <DateNTime>2012-01-01</DateNTime>
                      </Location>
                     </state>
                    </states>";

var stream = new System.IO.StringReader(xml);

var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Container));

var container = serializer.Deserialize(stream);

将对象序列化为 XML

//create and populate the container with your data here
//probably created when you hydrate your object from XML as in above.
var container = new Container();

//used to clean up unneeded namespaces
var xmlSerializerNamespace = new System.Xml.Serialization.XmlSerializerNamespaces();
xmlSerializerNamespace.Add(string.Empty, string.Empty);

var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Container));

var stream = new System.IO.StringWriter();

//serialize your object to a stream
serializer.Serialize(stream, container, xmlSerializerNamespace);

var yourXml = stream.ToString();

If you do not require using an IDictionary, I find it very easy to work with the XmlSerializer.

Models

[XmlRoot(ElementName="states")]
public class Container
{
    [XmlElement("state")]
    public List<State> States { get; set; }
}

public class State
{
    [XmlAttribute()]
    public string name { get; set; }

    [XmlElement("Location")]
    public List<Location> Locations { get; set; }
}

public class Location
{
    [XmlAttribute()]
    public string Name { get; set; }

    public string Address { get; set; }

    public DateTime DateNTime { get; set; }
}

Deserializing objects from XML

var xml = @"<?xml version='1.0' encoding='utf-16'?>
                    <states>
                     <state name ='Alaska'>
                      <Location Name='loc1'>
                       <Address>testadd1</Address>
                       <DateNTime>2012-01-01</DateNTime>
                      </Location>
                      <Location Name='loc2'>
                       <Address>add2</Address>
                       <DateNTime>2012-01-01</DateNTime>
                      </Location>
                     </state>
                    </states>";

var stream = new System.IO.StringReader(xml);

var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Container));

var container = serializer.Deserialize(stream);

Serializing objects to XML

//create and populate the container with your data here
//probably created when you hydrate your object from XML as in above.
var container = new Container();

//used to clean up unneeded namespaces
var xmlSerializerNamespace = new System.Xml.Serialization.XmlSerializerNamespaces();
xmlSerializerNamespace.Add(string.Empty, string.Empty);

var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Container));

var stream = new System.IO.StringWriter();

//serialize your object to a stream
serializer.Serialize(stream, container, xmlSerializerNamespace);

var yourXml = stream.ToString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文