[英]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.