将XElement添加到现有的XML文件中

问题描述:

我已经做了大量的研究,并且在任何地方我都会看到它说这应该起作用。每当我运行我的程序时,它都会通过以下错误:当程序到达xdoc.Root.Element时,“对象引用未设置为对象的实例”.....将XElement添加到现有的XML文件中

此代码片段位于主程序中。

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

任何帮助将是伟大的!

+0

调试是你的朋友。检查'null'值是从哪里开始的。 – MarcinJuraszek 2014-12-04 03:05:07

+0

它出现在xdoc文档类型中。我该如何解决这个问题? – 2014-12-04 03:11:22

我的猜测是“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()) 
));