c# - 如何修复关闭后插入的 XML 节点
问题描述
我正在从 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
解决方案
我的同事能够帮助我,也许这会帮助其他人
我变了
changeDoc.Add(elm);
至
changeDoc.Descendants("Client").First().Element("ClientLocationsList").Add(elm);
问题只是使用 add 告诉程序添加没有父对象的指定对象,这样做更新的方式告诉他们我想插入 ClienLocationsList 的第一个实例,它是 Client 的子对象
推荐阅读
- java - Crate db 指标与 jmx_exporter 的集成
- javascript - 将异步函数直接导出为模块不会加载到其他模块中
- python-3.6 - 为什么我的代码在 python2 中运行而不在 python3 中运行
- php - 更新具有特定条件的行时是否需要事务
- angular - Angular 10+ 将 base64 图像转换为表单数据
- c++ - 如何在 ImageMagick C++ 中将图像转换为字节数组
- spring-cloud - Spring cloud dataflow 使用 docker 创建 rabbitmq python 应用程序
- python - Photoshop的python脚本中的Windows COMError
- python - 如何将 Json 转换为数组?
- python - 从字符串python获取数字