[英]Adding XElement in to Existing XML File
I have done lots of research and everywhere I look it says this should work. 我做了很多研究,到处都有它说应该可行。 Every time I run my program it throughs the following error: "Object reference not set to an instance of an object" when the program reaches xdoc.Root.Element.....
每次我运行程序时,都会遇到以下错误:当程序到达xdoc.Root.Element .....时,“对象引用未设置为对象的实例”
This snippet is in the main program. 该代码段位于主程序中。
private void btn_save_Click(object sender, EventArgs e)
{
Certification cert = new Certification();
cert.CreateCertification(txt_certlevel.Text, txt_certnum.Text, txt_certagency.Text, dtp_cert.Value);
xmlfunction.Add(cert);
}
And this snippet is in a Class file seperate from the main program file. 并且此片段位于与主程序文件分离的Class文件中。
public void Add(Certification certification)
{
XDocument xdoc = XDocument.Load(pathString);
xdoc.Root.Element("Digital_Scuba_Log").Element("Diver").Element("Certifications").Add(new XElement("Certification_Card",
new XElement("Level", certification.Level),
new XElement("Agency", certification.Agency),
new XElement("Number", certification.Number),
new XElement("Date", certification.Date.ToString())
));
xdoc.Save(pathString);
}
Any help would be great! 任何帮助将是巨大的!
My guess is that "Digital_Scuba_Log" is the root node of your XML. 我的猜测是“ Digital_Scuba_Log”是XML的根节点。 In that case, when you use xdoc.Root, you're already traversing into that node.
在这种情况下,使用xdoc.Root时,您已经遍历了该节点。 Here are 2 ways to do it based on your XML.
这里有两种基于XML的方法。
"Digital_Scuba_Log" as your root node: 将“ Digital_Scuba_Log”作为您的根节点:
XDocument xDoc2 = XDocument.Parse("<Digital_Scuba_Log><Diver><Certifications></Certifications></Diver></Digital_Scuba_Log>");
xDoc2.Element("Digital_Scuba_Log")
.Element("Diver")
.Element("Certifications")
.Add(new XElement("Certification_Card",
new XElement("Level", certification.Level),
new XElement("Agency", certification.Agency),
new XElement("Number", certification.Number),
new XElement("Date", certification.Date.ToString())
));
With a root node on your xml: 在xml上具有根节点:
XDocument xDoc1 = XDocument.Parse("<root><Digital_Scuba_Log><Diver><Certifications></Certifications></Diver></Digital_Scuba_Log></root>");
xDoc1.Root.Element("Digital_Scuba_Log")
.Element("Diver")
.Element("Certifications")
.Add(new XElement("Certification_Card",
new XElement("Level", certification.Level),
new XElement("Agency", certification.Agency),
new XElement("Number", certification.Number),
new XElement("Date", certification.Date.ToString())
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.