将XElement添加到现有XML文件中

时间:2014-12-04 03:01:03

标签: c# xml visual-studio linq-to-xml

我做了很多研究,到处都看,它说这应该有效。每次我运行我的程序时都会遇到以下错误:"对象引用未设置为对象的实例"当程序到达xdoc.Root.Element .....

此代码段位于主程序中。

    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);
    }

此代码段位于与主程序文件分开的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);
    }

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

我的猜测是“Digital_Scuba_Log”是XML的根节点。在这种情况下,当您使用xdoc.Root时,您已经遍历到该节点。以下是基于XML的两种方法。

“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())
));

在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())
));