Build a new XML from two xmlnodelist

111 views Asked by At

How do we build a xml by getting values from two xmlnodelist,

Ex---> Xmlnodelist1:

<D>
  <F a="1" b="2" c="3">
     <B d="4" e="5" f="6" g="7"/>
     <B d="5" e="5" f="11" g="7"/>
     <B d="6" e="5" f="23" g="8"/>
     <B d="7" e="5" f="45" g="9"/>
   </F>
</D>  

Xmlnodelist2:

<Z aa="1">
       <s e="4" ee="5" ae="6"/>
       <s e="5" ee="55" ae="6"/>
       <s e="6" ee="555" ae="6"/>
       <s e="7" ee="5555" ae="6"/>
    </Z>

Here compare "d" value in xmlnodelist1 with "e" value in xmlnodelist2 and get values of "g","f", and "ae" and build a xml like ->

 <Root>
         <T g="7" f="45" ar="6">
         <T g="7" f="45" ar="6">
         <T g="7" f="45" ar="6">
         <T g="7" f="45" ar="6">
    </Root> 

This is just an example. Please reply with an answer. Thanks

1

There are 1 answers

0
Brice2Paris On

You could use Linq to Xml. The sample below does not provide the exact result of your example because I don't exactly understand the relation between the 2 lists but it's a beginning :

        XElement xml1 =
            XElement.Parse("<D>" +
                            "  <F a=\"1\" b=\"2\" c=\"3\">" +
                            "     <B d=\"4\" e=\"5\" f=\"6\" g=\"7\"/>" +
                            "     <B d=\"5\" e=\"5\" f=\"11\" g=\"7\"/>" +
                            "     <B d=\"6\" e=\"5\" f=\"23\" g=\"8\"/>" +
                            "     <B d=\"7\" e=\"5\" f=\"45\" g=\"9\"/>" +
                            "  </F>" +
                            "</D>");

        XElement xml2 =
            XElement.Parse("<Z aa=\"1\">" +
                            "  <s e=\"4\" ee=\"5\" ae=\"6\"/>" +
                            "  <s e=\"5\" ee=\"55\" ae=\"6\"/>" +
                            "  <s e=\"6\" ee=\"555\" ae=\"6\"/>" +
                            "  <s e=\"7\" ee=\"5555\" ae=\"6\"/>" +
                            "</Z>");
        // I join list1 and list2 with attribute d and e
        IEnumerable<XElement> result = from list1 in xml1.Descendants("B")
                                       join list2 in xml2.Descendants("s")
                                       on list1.Attribute("d").Value equals list2.Attribute("e").Value
                                       select new XElement("T", new XAttribute("g", list1.Attribute("g").Value),
                                           new XAttribute("f", list1.Attribute("f").Value),
                                           new XAttribute("ar", list2.Attribute("ae").Value));
        var test = new XElement("Root", result);

And the result is :

<Root>
  <T g="7" f="6" ar="6" />
  <T g="7" f="11" ar="6" />
  <T g="8" f="23" ar="6" />
  <T g="9" f="45" ar="6" />
</Root>