curiousDev
curiousDev

Reputation: 437

Split into xml files retaining few tags from base xml file using linq

I have this xml and want to split to individual xml files based on the <order> tag count retaining few tags from base xml.Since I am new to play with xml and linq, I was just searching in google and questions on stack overflow didnt meet my requirements.

<OrderList>
<Source>xml</Source>
<Organisation>org</Organisation>
<CreationDate>12/14/2015</CreationDate>
<Orders>
 <Order>
    <Name> Mobile </Name>
    <Price> 50.00</Price>
    <Quantity> 1 </Quantity>
 </Order>
  <Order>
    <Name> Accessories </Name>
    <Price> 50.00</Price>
    <Quantity> 5 </Quantity>
 </Order>
 </Orders>
</OrderList>

So File1.xml should be

<OrderList>
<Source>xml</Source>
<Organisation>org</Organisation>
<CreationDate>12/14/2015</CreationDate>
<Orders>
 <Order>
    <Name> Mobile </Name>
    <Price> 50.00</Price>
    <Quantity> 1 </Quantity>
 </Order>
 </Orders>
 </OrderList>

File2.xml

<OrderList>
<Source>xml</Source>
<Organisation>org</Organisation>
<CreationDate>12/14/2015</CreationDate>
<Orders>
 <Order>
    <Name> Accessories </Name>
    <Price> 50.00</Price>
    <Quantity> 5 </Quantity>
 </Order>
 </Orders>
 </OrderList>

Previous questions in stackoverflow explains to split the tags into xml file but I want to retain few values from base file also.Can any please help with this with Linq and XElement?

Upvotes: 0

Views: 378

Answers (1)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

If you want to split the Orders in two OrderList you can try something like this, you will dont need to create the same node, it will be copied from ordersXML, and the new Orders will be created:

XElement ordersXML = XElement.Parse(XML_ORDERS);        
var ordersElement = ordersXML.Element("Orders");
var orders = ordersElement.Elements("Order");
var newOrdersList = orders.Select(x => new XStreamingElement("OrderList", ordersXML.Elements().Where(e => e.Name!="Orders"), new XElement("Orders",x)));

So see my .NET Fiddle.

Upvotes: 4

Related Questions