Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...