Добавьте XElement в другой XElement в указанном c месте - PullRequest
0 голосов
/ 07 февраля 2020

Мой XML:

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

Я хочу добавить новый элемент учетной записи до того, как идентификатор клиента = 2. у меня есть xml в xelement, и я хочу добавить другой xelement к первому. как это сделать? Спасибо за помощь.

1 Ответ

1 голос
/ 07 февраля 2020

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);
...