如何解决如何通过控制 C# 中的属性 ID 在 XML 中添加节点?
我有一个这样的 XML
<Root>
<Branch>
<Child Id="0">
<Reference Name="B0"/>
<Details Number="2">
<Detail Height="50"/>
<Detail Weight="3"/>
</Details>
</Child>
<Child Id="2">
<Reference Name="B2"/>
<Details Number="2">
<Detail Height="55"/>
<Detail Weight="3.5"/>
</Details>
</Child>
</Branch>
</Root>
我想在 Child ID=0 数据块之后为 Child ID=1 添加一个新的数据块
解决方法
将新孩子添加到当前列表可能更容易。然后给孩子排序。见下面的xml linq代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XElement newChild = new XElement("Child",new object[] {
new XAttribute("Id","1"),new XElement("Reference",new XAttribute("Name","B1")),new XElement("Details",new object[] {
new XAttribute("Number","2"),new XElement("Detail",new XAttribute("Height","52")),new XAttribute("Weight","3.25"))
})
});
XDocument doc = XDocument.Load(FILENAME);
XElement branch = doc.Descendants("Branch").FirstOrDefault();
branch.Add(newChild);
List<XElement> orderedChildren = branch.Elements("Child").OrderBy(x => (int)x.Attribute("Id")).ToList();
XElement newBranch = new XElement("Branch",orderedChildren);
branch.ReplaceWith(newBranch);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。