繁体   English   中英

如何使用C#.net在XMl文件中插入迭代元素?

[英]How to insert iteration Element in XMl file using C#.net?

我想根据我的要求插入迭代元素(信号),如下面的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文件插入?

您还没有显示信号数据方面的功能,但是您应该能够在最后一个现有的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其余部分很好地集成的方式之一。

编辑:通过您的注释判断,您已经有数据,但是在数据表中。 您仍然可以使用DataTable.AsEnumerable().Select(row => ...)来应用相同的方法,但是我个人强烈考虑首先将其转换为强类型集合,以使代码简单易维护。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM