C# 如何在另一个子节点中添加子节点

C# 如何在另一个子节点中添加子节点,c#,xml,linq,xelement,C#,Xml,Linq,Xelement,如何将另一个概念节点(concept Key=“1234”R)添加到Rssd=3284070的子Rssd节点 在C#中,我使用XElements来构造所有XML。我需要linq声明吗 <Root> <Rssd Key="3900455" /> <Rssd Key="4442961" /> <Rssd Key="4442961" /> <Rssd Key="4442970" /> <Rssd Key="3284070"&g

如何将另一个概念节点(concept Key=“1234”R)添加到Rssd=3284070的子Rssd节点 在C#中,我使用XElements来构造所有XML。我需要linq声明吗

<Root>
 <Rssd Key="3900455" />
 <Rssd Key="4442961" />
 <Rssd Key="4442961" />
 <Rssd Key="4442970" />
 <Rssd Key="3284070">
   <Concept Key="1662">
   <Concept Key="1668">
 </Rssd>
</Root>

LINQ仅用于查询(选择数据集的一部分),不用于修改数据集。在这里,我使用它来获取
Rssd
元素,我们要在其中添加新的
概念
元素

XDocument xDocument = ...

XElement parentElement = (from rssdElement in xDocument.Descendants("Rssd")      // Iterates through the collection of all Rssd elements in the document
                          where rssdElement.Attribute("Key").Value == "3284070"  // Filters the elements to get only those which have the correct Key attribute value
                          select rssdElement).FirstOrDefault();                  // Gets the first element that satisfy the above condition (returns null if no element has been found)

if (parentElement == null)
    throw new InvalidDataException("No Rssd element found with the key \"3284070\"");

XElement newConceptElement = new XElement("Concept");  // Creates a new Concept element
newConceptElement.Add(new Attribute("Key", "1234"));   // Adds an Key attribute to the element with the specified value

parentElement.Add(newConceptElement);                  // Adds the new Concept element to the Rssd element
XDocument xDOC=XDocument.Load(文件路径);
foreach(xDOC.substands(“Rssd”)中的XElement xele)
{
if(xele.Attribute(“Key”).Value==“3284070”)
{
XElement xele1=XElement.Parse(“”);
xele.Add(xele1);
//如果您只想添加一个子节点,请应用中断,否则添加继续添加根据您的要求,我只添加一个节点
打破
}
}
保存(文件路径);
XDocument xDOC = XDocument.Load(FilePath);
            foreach (XElement xele in xDOC.Descendants("Rssd"))
            {
                if (xele.Attribute("Key").Value == "3284070")
                {
                    XElement xele1 = XElement.Parse("<Concept Key='1234' />");
                    xele.Add(xele1);
                    //Apply a break if you wish to add only one child node else add keep on adding as per your requirement, I am adding only one node 
                    break;
                }
            }
            xDOC.Save(FilePath);