-1

I have a XML file. I am looлing for help to create multiple xml files from this xml file where ever it find different EmplId.

I tried to retrieve the distinct EmplId But not sure how to break the xml and loop through the entire xml file further.

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

First Xml EmplID =1

<?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>

Second Xml EmplId = 2

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

Third Xml - EmplId = 3

<?xml version="1.0" encoding="utf-8"?>
<Connected>
  <Emp>
    <A.EMPLID>3</A.EMPLID>
    <A.Add>XXXXXXX</A.Add>
  </Emp>
</Connected>

I have used below code to count distinct emplid

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:/Sample - code test.xml");
XmlNodeList count = xmlDoc.SelectNodes(@"//Connected/Emp/A.EMPLID");

int i = count.Cast<XmlNode>().Select(a => a.InnerText).Distinct().Count();
Console.WriteLine(i);
2

1 Answer 1

2

Linq2xml much more convenient.

var xml = XElement.Load("test.xml");

var grouped = xml.Elements("Emp")
    .GroupBy(emp => emp.Element("A.EMPLID").Value);

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

    x.Save("file" + group.Key + ".xml");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.