本文介绍了如何将记录包含到XML元素C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨...我想请你们帮我创建这个xml文件...我已经尝试过上面这段代码,但是我有一些错误......即使我在ForFor之外声明了docRecords循环它给了我一个错误:
Hi...I would like to please you guys to help me creating this xml file...I've tried with this code above but I've got some Errors...even when I declarate docRecords outside of For loop it gives me an Error:
An unhandled exception of type 'System.NullReferenceException' occurred in XMLGenUsingLINQ.exe
附加信息:对象引用不是定义为对象实例......类似的东西......我从我的语言翻译过来了。
这是我想得到的架构:
Additional information: The object reference not defined as Object Instance...something like that...I've translated from my language :)
Here is the Schema I want to get:
<Report>
<Versao>1</Versao>
<Details>
<Record>
<ID>1</ID>
<Reference>20171</Reference>
</Record>
<Record>
<ID>2</ID>
<Reference>20172</Reference>
</Record>
</Details>
</Report>
我的尝试:
我是试过这个:
What I have tried:
I've tried this:
XDocument docHeader = new XDocument(
new XElement("Report",
new XElement("Versao", "1"),
new XElement("Details", "")
));
for (int i = 0; i < 2; i++)
{
var docRecords = new XElement("Record",
new XElement("ID", i.ToString()),
new XElement("Reference", "2017" + i.ToString())
);
}
docHeader.Element("Details").Add(docRecords);
using (var writer = new XmlTextWriter("C:\\Reports\\MyReport.xml", new UTF8Encoding(false)))
{
docHeader.Save(writer);
}
推荐答案
for (int i = 0; i < 2; i++)
{
var docRecords = new XElement("Record",
new XElement("ID", i.ToString()),
new XElement("Reference", "2017" + i.ToString())
);
docHeader.Element("Report").Element("Details").Add(docRecords);
}
这篇关于如何将记录包含到XML元素C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!