在特定位置的另一个XElement中添加XElement

我的XML:

<Bank>
    <Customer id="0">
        <Accounts>
            <Account id="0" />
            <Account id="1" />
        </Accounts>
    </Customer>
    <Customer id="2">
        <Accounts>
            <Account id="0" />
        </Accounts>
    </Customer>
</Bank>

我想在客户ID = 2之前添加新的帐户元素。 我在xelement中有这个xml,我想向其他第一个添加其他xelement。怎么办? 谢谢您的帮助。

评论
  • 院子里画沙
    院子里画沙 回复

    linq-to-xml使这个变得容易:

    // Parse our XML document to an XDocument
    var xml = @"<Bank>
        <Customer id=""0"">
            <Accounts>
                <Account id=""0"" />
                <Account id=""1"" />
            </Accounts>
        </Customer>
        <Customer id=""2"">
            <Accounts>
                <Account id=""0"" />
            </Accounts>
        </Customer>
    </Bank>";
    var doc = XDocument.Parse(xml);
    
    // Create our new Customer to add
    var newCustomer = new XElement("Customer",
        new XAttribute("id", "1"),
        new XElement("Accounts",
            new XElement("Account", new XAttribute("id", "0"))
        )
    );
    
    // Find the customer with id="2"
    var customer2 = doc.Root.Elements("Customer").First(x => x.Attribute("id").Value == "2");
    // Add the new customer before the customer with id="2"
    customer2.AddBeforeSelf(newCustomer);