在.net中生成XML
本文关键字:XML net | 更新日期: 2023-09-27 18:16:46
我正在尝试生成以下格式的XML:
<ImportSession>
<Batches>
<Batch>
<BatchFields>
<BatchField Name="Field1" Value="1" />
<BatchField Name="Field2" Value="2" />
<BatchField Name="Field3" Value="3" />
</BatchFields>
<Batch>
<Batches>
</ImportSession>
我有以下代码:
XmlDocument doc = new XmlDocument();
XmlElement importSession = doc.CreateElement("ImportSession");
XmlElement batches = doc.CreateElement("Batches");
XmlElement batch = doc.CreateElement("Batch");
XmlElement batchFields = doc.CreateElement("BatchField");
doc.AppendChild(importSession);
XmlNode importSessionNode = doc.FirstChild;
importSessionNode.AppendChild(batches);
XmlNode batchesNode = importSessionNode.FirstChild;
batchesNode.AppendChild(batch);
XmlNode batchNode = batchesNode.FirstChild;
int numBatchFields = 9;
for (int j = 0; j < numBatchFields; j++)
{
batchNode.AppendChild(batchFields);
XmlElement batchfields = (XmlElement)batchNode.FirstChild;
batchfields.SetAttribute("Name", "BatchPrevSplit");
batchfields.SetAttribute("Value", j.ToString());
}
我的问题是,它没有添加batchfield标签。它加了一个,所以我得到:
<ImportSession>
<Batches>
<Batch>
<BatchField Name="BatchPrevSplit" Value="8" />
</Batch>
</Batches>
</ImportSession>
似乎是因为我试图将相同的子元素添加到batchNode节点,它只是覆盖现有标记中的数据。我试着输入
XmlElement batchfields = (XmlElement)batchNode.ChildNodes.Item(j);
代替
XmlElement batchfields = (XmlElement)batchNode.FirstChild;
,但它不追加另一个孩子的batchNode,如果我使用相同的元素,所以只有一个孩子。谁能告诉我怎么才能做到这一点?
像这样重写你的for
循环:
for (int j = 0; j < numBatchFields; j++)
{
XmlElement batchFields = doc.CreateElement("BatchField");
batchFields.SetAttribute("Name", "BatchPrevSplit");
batchFields.SetAttribute("Value", j.ToString());
batchNode.AppendChild(batchFields);
}
LINQ to XML将省去你的麻烦…
var xml = new XElement("ImportSession",
new XElement("Batches",
new XElement("Batch",
new XElement("BatchFields",
from j in Enumerable.Range(0,9)
select new XElement("BatchField",
new XAttribute("Name", string.Format("Field{0}", j)),
new XAttribute("Value", j)
)
)
)
)
);