将第二级元素添加到XML

时间:2015-10-19 15:10:10

标签: c# .net xml

我有一个XML文件:

<uploads>
  <upload backupid="3">
    XXXXXXXXX
  </upload>
</uploads>

如何添加元素(甚至更多)来代替XXX(对于给定的backupid)?

<file filename="XXX">HASH-CODE</file>

我已尝试过以下内容:

public static void AddFileToExistingUpload(int lastUsedID, string fileName, string generatedHash)
{
    var xdoc = LoadUploadsXML();
    var element = xdoc.Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));
    element.Add(new XElement("file", generatedHash, new XAttribute("filename", fileName)));
    SaveUploadXML(xdoc);
}

但我得到的只是:

  

未处理的类型&#39; System.NullReferenceException&#39;   发生

1 个答案:

答案 0 :(得分:1)

xdoc只有一个uploads元素,upload位于其中:

 var element = xdoc.Element("uploads").Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));

或插入Root代替:

 var element = xdoc.Root.Elements("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));

或使用Descendants

    var element = xdoc.Descendants("upload").SingleOrDefault(x => x.Attribute("backupid").Value.Equals(lastUsedID));