到XML/Xdocument世界的Noobie。尝试创建一个具有可变数量的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;
}发布于 2018-06-04 18:58:12
它抛出异常,因为还没有一个元素。要构建想要的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中的每个项添加一个新的DataFields元素,作为DataFields的子元素。
https://stackoverflow.com/questions/50686852
复制相似问题