【问题标题】:How to insert iteration Element in XMl file using C#.net?如何使用 C#.net 在 XMl 文件中插入迭代元素?
【发布时间】:2010-11-19 08:22:26
【问题描述】:

我想根据我的要求插入迭代元素(信号),如下面的 xml 输出。

    <?xml version="1.0" encoding="UTF-8"?>
    <WIUConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Timestamp>2006-05-04T18:13:51.0Z</Timestamp>
      <WIUAddress>WIUAddress0</WIUAddress>
      <WIUName>WIUName0</WIUName>
      <BeaconFlag>Y</BeaconFlag>
      <EncryptedHMACkey>30</EncryptedHMACkey>
      <DeviceStatusConfigVersion>DeviceStatusConfigVersion0</DeviceStatusConfigVersion>
      <Signal>
        <SiteDeviceId>SiteDeviceId0</SiteDeviceId>
        <SiteName>SiteName0</SiteName>
        <TrackName>TrackName0</TrackName>
      </Signal>
      <Signal>
        <SiteDeviceId>SiteDeviceId1</SiteDeviceId>
        <SiteName>SiteName1</SiteName>
        <TrackName>TrackName1</TrackName>
      </Signal>
      <Signal>
      .
      .
      .
      </Signal>
   </WIUConfig>

我如何使用 C#.net LINQ to XML 实现这个迭代概念

这是我的代码:

                XDocument xdco = new XDocument(
                new XDeclaration("1.0", "utf-8", "Yes"),
                new XComment("WIU Configurations"),
                new XElement("WIUConfig",
                    new XElement("Timestamp", datetime),
                    new XElement("WIUAddress", ds.Tables[0].Rows[0][0].ToString()),
                    new XElement("WIUName", ds.Tables[0].Rows[0][1].ToString()),
                    new XElement("BeaconFlag", "Y"),
                    new XElement("EncryptedHMACkey", ds1.Tables[0].Rows[0][0].ToString()),
                    new XElement("DeviceStatusConfigSCAC", ds.Tables[0].Rows[0][0].ToString()),
                    new XElement("DeviceStatusConfigTableId", ds.Tables[0].Rows[0][0].ToString()),
                    new XElement("DeviceStatusConfigVersion", ds.Tables[0].Rows[0][0].ToString()),

                    **????????(iteration code) **

                    ));

xdco.Save(OutPath);

从上面的代码中如何插入带有 XML 文件的迭代元素?

【问题讨论】:

  • 您的信号是否在某种集合中?
  • 使用以下代码解决: for (int i = 0; i

标签: c# asp.net xml c#-3.0 linq-to-xml


【解决方案1】:

您还没有在信号数据方面显示您所拥有的内容,但您应该能够在您最后存在的new XElement 行之后直接执行类似的操作:

signals.Select(signal => new XElement("Signal",
    new XElement("SiteDeviceId", signal.SiteDeviceId),
    new XElement("SiteName", signal.SiteName),
    new XElement("TrackName", signal.TrackName)
))

LINQ to XML 足够聪明,可以对可迭代的参数进行递归。这是它与 LINQ 的其余部分很好地集成的方式之一。

编辑:根据您的 cmets 判断,您已经拥有数据但在 DataTable 中。您仍然可以使用 DataTable.AsEnumerable().Select(row =&gt; ...) 应用相同的方法,但我个人强烈考虑先将其转换为强类型集合,以保持代码简单和可维护。

【讨论】:

    【解决方案2】:

    您可以从中创建“业务对象”的中间集合,然后使用 DataContractSerializer 对其进行序列化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多