2010-11-19 57 views
0

我想按照我的要求插入迭代元素(信号),如下面的xml输出。如何使用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文件迭代元素?

+0

你的信号在某种集合中? (新的XElement(“Signal”,new XElement(“SiteDeviceId”))使用以下代码解析的: – 2010-11-19 08:28:53

+0

:for(int i = 0; i Jeyavel 2010-11-19 08:36:06

回答

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其余部分非常好地集成的方式之一。

编辑:通过您的评论判断,您已经拥有数据但是在DataTable中。你仍然可以使用相同的方法使用DataTable.AsEnumerable().Select(row => ...),但个人而言,我强烈建议首先将其转换为强类型集合,以保持代码的简单性和可维护性。

+0

谢谢Jon Skeet ... – Jeyavel 2010-11-19 08:41:11

0

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

相关问题