【问题标题】:How to fix XML Nodes being inserted after closing如何修复关闭后插入的 XML 节点
【发布时间】:2019-12-26 00:53:27
【问题描述】:

我正在从 sql 数据库中加载记录并将它们插入到 XML 树中,但是在我想要它们的列表关闭之后插入新记录。

我尝试过使用 addafterself、addbeforeself 这两种方法都会导致空引用异常。

这是我用来填充 xml 的函数

 private void FillXml(List<ClientCrosswalk> clients)
        {

            XElement doc = XElement.Load(cFolder + @"\Files\emptyClientXMLMod.xml");
            List<XElement> elements = new List<XElement>();
            //Add the first client to the list to avoid overwriting
            foreach (var node in doc.Descendants("ClientLocation"))
            {
                elements.Add(node);
                node.Element("Description").Value = clients[0].AcctNo.ToString() + " " + clients[0].AcctName.ToString();
                node.Element("LocationName").Value = clients[0].DivCode.ToString();
            }
            clients.RemoveAt(0);
            doc.Save(cFolder + @"\Outbox\clientSIE.xml");
            //Build a new xml tree for each respective client and add it to the Client list
            foreach (var client in clients)
            {
                foreach (var elm in elements)
                {
                    elm.Element("Description").Value = client.AcctNo.ToString() + " " + client.AcctName.ToString();
                    elm.Element("LocationName").Value = client.DivCode.ToString();
                    doc.Add(elm);
                }
            }
            doc.Save(cFolder + @"\Outbox\clientSIE.xml");
        }

我希望生成的 xml 是

<Client>
<ClientLocationsList>
<ClientLocation>
data set1
</ClientLocation>
<ClientLocation>
data set2
</ClientLocation>
</ClientLocationsList>
</Client>

我得到的是

<ClientLocationsList>
<ClientLocation>
data set1
</ClientLocation>
</ClientLocationsList>
</Client>
data set2

【问题讨论】:

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


    【解决方案1】:

    我的同事能够帮助我,也许这会帮助其他人

    我变了

    changeDoc.Add(elm);
    

    changeDoc.Descendants("Client").First().Element("ClientLocationsList").Add(elm);
    

    问题只是使用 add 告诉程序添加没有父对象的指定对象,这样做更新的方式告诉他们我想插入 ClienLocationsList 的第一个实例,它是 Client 的子对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多