xdocument 从头开始​​创建

xdocument create from scratch

XML/Xdocument 世界的新手。 尝试创建一个具有可变数量的 DataField 元素的 Xdocument,这些元素作为元组列表传入。 此文档用作 API 调用的一部分,用于编辑远程服务器上记录中的字段。 当我尝试在 foreach 循环中添加 DataField 元素时,xdoc 被视为 Null。所以我不断收到 NullReferenceException 错误。 为什么 xdoc 或其 XElements 在我刚创建时 = null? 我知道这不是一个困难的情况,但在过去的几天里,我浏览了几个网站 很明显我没有得到一些非常基本的东西。

public XDocument MakeXDoc(string frmID, string prj, List<Tuple<string, string, string>> frmdata)
{
    XNamespace ns = "http://xxxxxxx.yyyyyy.com/api/v1/";
    var xdoc = new XDocument(
         new XDeclaration("1.0", "utf-8", null),
         new XElement(ns + "ProjectDataRequest",
         new XElement(ns + "Project",
         new XElement(ns + "DataFields", new XAttribute("ProjectId", prj), new XAttribute("FormId", frmID),
         new XElement(ns + "DataField" , new XAttribute("DataFieldId", ""), new XAttribute("Value", "") )))));

        foreach (Tuple<string, string, string> fld in frmdata)
        {
            XElement xdf = new XElement(ns + "DataField", new XAttribute("DataFieldId", fld.Item1.ToString()), new XAttribute("Value", fld.Item3.ToString()));
            xdoc.Element(ns + "DataField").Add(xdf);
        }

    return xdoc;
}

它抛出异常,因为还没有元素。要构建所需的 XML,您可以使用 LINQ 的 Select:

XDocument MakeXDoc(string frmID, string prj, List<Tuple<string, string, string>> frmdata)
{
    XNamespace ns = "http://xxxxxxx.yyyyyy.com/api/v1/";
    var xdoc = new XDocument(
        new XDeclaration("1.0", "utf-8", null),
        new XElement(ns + "ProjectDataRequest",
        new XElement(ns + "Project",
        new XElement(ns + "DataFields", new XAttribute("ProjectId", prj), new XAttribute("FormId", frmID),
        frmdata.Select(d => new XElement(ns + "DataField", new XAttribute("DataFieldId", d.Item1), new XAttribute("Value", d.Item3)))))));

    return xdoc;
}

它为 frmdata 中的每个项目添加一个新的 DataField 元素作为 DataFields 的子元素。