繁体   English   中英

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

[英]Add XElement in another XElement in specific location

我的 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM