【发布时间】:2020-09-01 08:09:02
【问题描述】:
我正在尝试制作一个深度嵌套的 XML 文件,我想在其中插入来自另一个文件的一些数据。
现在的样子:
<Documents Count="1">
<Item DATE="2020-09-01" CREATEDBY="TestUser">
<Row ITEMID="" ACTIVE="" />
</Item>
</Documents>
我希望它看起来像这样:
<Documents Count="1">
<Item DATE="2020-09-01" CREATEDBY="TestUser">
<Row ITEMID="" ACTIVE="" />
<Row ITEMID="" ACTIVE="" />
<Row ITEMID="" ACTIVE="" />
<Row ITEMID="" ACTIVE="" />
</Item>
</Documents>
问题是节点“Item”内部必须有很多行(节点“Row”),我想通过读取它的每一行来从另一个文件填充数据并执行我需要的操作for 循环。 我被卡住了,因为它不允许我在其中添加 for 循环,有没有办法以某种方式在其中插入 for 循环?
谢谢。
这是我目前编写的代码:
class Program
{
static void Main(string[] args)
{
var xmlData = new XmlData();
xmlData.documents.documentsItem.Add(new DocumentsItem()
{
DATE = DateTime.Now.ToString("yyyy-MM-dd"),
CREATEDBY = "TestUser",
documentsRow = new List<DocumentsRow>()
{
//<-- I want to insert a 'for' loop in here, but it won't allow me to do that
new DocumentsRow()
{
ITEMID = "",
ACTIVE = "",
}
}
});
xmlData.documents.Count = xmlData.documents.documentsItem.Count;
using (StreamWriter sw = new StreamWriter(@"c:\a\test.xml", false, Encoding.UTF8))
{
new XmlSerializer(typeof(XmlData)).Serialize(sw, xmlData);
}
}
}
public class XmlData
{
[XmlElement("Documents")]
public Documents documents = new Documents();
[XmlIgnore]
public DocumentsRow documentsRow = new DocumentsRow();
}
public class Documents
{
public Documents()
{
documentsItem = new List<DocumentsItem>();
}
[XmlAttribute]
public int Count { get; set; }
[XmlElement("Item")]
public List<DocumentsItem> documentsItem { get; set; }
}
public class DocumentsItem
{
public DocumentsItem()
{
documentsRow = new List<DocumentsRow>();
}
[XmlAttribute]
public string DATE { get; set; }
[XmlAttribute]
public string CREATEDBY { get; set; }
[XmlElement("Row")]
public List<DocumentsRow> documentsRow { get; set; }
}
public class DocumentsRow
{
[XmlAttribute]
public string ITEMID { get; set; }
[XmlAttribute]
public string ACTIVE { get; set; }
}
【问题讨论】:
-
documentsRow = new List<DocumentsRow>() {在那个括号里面,你在collection initializer里面。不在普通的代码块中。
标签: c# .net xml for-loop xml-serialization