Search code examples
c#xmlxelement

Create XMLs from xmls using C#


I have a XML file. I am looking for help to create multiple xml files from this xml file . The new xml will have the all the node with the same EmpID.I am using C# code and able to create xmls Xml looks like this -

<?xml version="1.0" encoding="utf-8"?>
      <Connected>
      <Emp>
          <A.EMPLID>1</A.EMPLID>
          <A.Phone>12##</A.Phone>
      </Emp>
      <Emp>
          <A.EMPLID>1</A.EMPLID>
          <A.Add>XXXXXXX</A.Add>
      </Emp>
      <Emp>
          <A.EMPLID>2</A.EMPLID>
         <A.Phone>##34</A.Phone>
      </Emp>
      <Emp>
         <A.EMPLID>3</A.EMPLID>
      </Emp>
      <Emp>
         <A.EMPLID>3</A.EMPLID>
         <A.Add>XXXXXXX</A.Add>
     </Emp>
    </Connected>

Output will be 3 different Xml for 3 different EmplId

1.xml

 <Connected>
     <Emp>
      <A.EMPLID>1</A.EMPLID>
      <A.Phone>12##</A.Phone>
     </Emp>
    <Emp>
      <A.EMPLID>1</A.EMPLID>
      <A.Add>XXXXXXX</A.Add>
    </Emp>
</Connected>

2.xml

  <Connected>
      <Emp>
      <A.EMPLID>2</A.EMPLID>
      <A.Phone>##34</A.Phone>
      </Emp>
  </Connected>

3.Xml

 <Connected>
     <Emp>
         <A.EMPLID>3</A.EMPLID>
     </Emp>
     <Emp>
         <A.EMPLID>3</A.EMPLID>
         <A.Add>XXXXXXX</A.Add>
     </Emp>
 </Connected>

I am trying to do that C# code. Using XElement

      XElement x = new XElement("Connected",new XElement("Emp",new XElement("A.EMPLID", group.Key),group.Select(g => g.Elements().Where(e =>e.Name != "A.EMPLID"))));

But It is creating some thing like this:

<?xml version="1.0" encoding="utf-8"?>
<Connected>
<Emp>


<A.EMPLID>1</A.EMPLID>


<A.Phone>12##</A.Phone>


<A.Add>XXXXXXX</A.Add>


</Emp>


</Connected>   

I need 3 xmls that will be generated for Empld but nodes should be exactly in same order.


Solution

  • Using xml linq :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                string ident = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Connected></Connected>";
    
                XDocument doc = XDocument.Load(FILENAME);
    
                var groups = doc.Descendants("Emp").GroupBy(x => (string)x.Element("A.EMPLID")).ToList();
                foreach (var group in groups)
                {
                    XDocument doc1 = XDocument.Parse(ident);
                    XElement root = doc1.Root;
    
                    root.Add(group);
    
                    doc1.Save(@"c:\temp\test" + group.Key + ".xml");
                }
    
            }
        }
    }