Link to home
Start Free TrialLog in
Avatar of Victor  Charles
Victor CharlesFlag for United States of America

asked on

Help with changing order of data element using VB.NET

Hi,

How do you loop through an xml file and change the order of a data element? For example if my xml file contains

<Root>
<Table1>
<ID>1</ID>
<Item1><Item1>
<Item3><Item3>
<Item4><Item4>
<Item2><Item2>
</Table1>
</Root>

I would like to move the last data element (Item2) below the Item1 data element.

<Root>
<Table1>
<ID>1</ID>
<Item1><Item1>
<Item2><Item2>
<Item3><Item3>
<Item4><Item4>
</Table1>
</Root>

Thanks,

Victor
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Hi Victor;

This should do it.

'' Locations of where to read and save the XML files
Dim inputXML As String = "Path and file name to XML file"
Dim saveXML As String = "Path and file name of where to save XML file"

'' Load XML document
Dim xdoc As XDocument = XDocument.Load(inputXML)

'' Order the ItemX in each Table1 node
Dim results = (From n In xdoc.Descendants("Table1") _
               Let items = n.Elements().OrderBy (Function(x) x.Name.ToString() ) _
               select n, items ).ToList()

'' Update the xdoc 
results.ForEach( Sub(node) node.n.ReplaceAll(node.items))

'' Save to the file system
xdoc.Save(saveXML)

Open in new window

Avatar of Victor  Charles

ASKER

Hi Fernando,

The names I gave was in example, in my project they are different.

<Root>
 <Table1>
 <ID>1</ID>
 <NSC><NSC>
 <NSN><NSN>
 <FIF><FIF>
 <AGD><AGD>
 </Table1>
 </Root>

Would like to move AGD under NSC.

Thanks,

Victor
Hi Victor;

Working with XML documents or fragments is very dependent on the XML schema/structure and so asking questions really requires the actual names of node and the structure of the document and if multiple nodes are involved.

Is it possible for the XML to have more then one Table1 node with multiple AGD node that have to move within their own parents node beneath NSC node?
Hi Fernando,

Yes, the xml file contains multiple records for <table1>. For example

<Root>
  <Table1>
  <ID>1</ID>
  <NSC><NSC>
  <NSN><NSN>
  <FIF><FIF>
  <AGD><AGD>
  </Table1>
<Table1>
  <ID>2</ID>
  <NSC><NSC>
  <NSN><NSN>
  <FIF><FIF>
  <AGD><AGD>
  </Table1>
<Table1>
  <ID>3</ID>
  <NSC><NSC>
  <NSN><NSN>
  <FIF><FIF>
  <AGD><AGD>
  </Table1>
<Table1>
  <ID>4</ID>
  <NSC><NSC>
  <NSN><NSN>
  <FIF><FIF>
  <AGD><AGD>
  </Table1>
  </Root>

Thanks,

Victor
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.
Thank You!