Moving an XML node up or Down

G

Guest

Hi,

Can anyone tell me how to move a node up or down in an xml document? For
example:

<root>
<field name="1"/>
<field name="2"/>
<field name="3"/>
</root>

I would like to move the field node name="3" up one position.

TIA

Ben
 
S

sloan

You might want to do a search for

Xml to Xml Transformation

...

This takes one Xml, uses an Xsl, to make another Xml (as opposed to an
output html file).

That might be the hint you're looking for.

...
 
M

Martin Honnen

Ben said:
Can anyone tell me how to move a node up or down in an xml document? For
example:

<root>
<field name="1"/>
<field name="2"/>
<field name="3"/>
</root>

I would like to move the field node name="3" up one position.

DOM manipulation with InsertBefore can do that e.g.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = false;
xmlDocument.Load(@"file.xml");

XmlNode fieldNode = xmlDocument.SelectSingleNode(
@"/root/field[@name = '3']");

if (fieldNode != null) {
fieldNode.ParentNode.InsertBefore(fieldNode,
fieldNode.PreviousSibling);
}

// save changes somewhere
// in this example simply the console to show changes
xmlDocument.Save(Console.Out);

Note that white space can be an issue when deciding what "up one
position" means.
 
G

Guest

Hi Martin,

Your code sample worked great! Thanks!

Ben

Martin Honnen said:
Can anyone tell me how to move a node up or down in an xml document? For
example:

<root>
<field name="1"/>
<field name="2"/>
<field name="3"/>
</root>

I would like to move the field node name="3" up one position.

DOM manipulation with InsertBefore can do that e.g.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.PreserveWhitespace = false;
xmlDocument.Load(@"file.xml");

XmlNode fieldNode = xmlDocument.SelectSingleNode(
@"/root/field[@name = '3']");

if (fieldNode != null) {
fieldNode.ParentNode.InsertBefore(fieldNode,
fieldNode.PreviousSibling);
}

// save changes somewhere
// in this example simply the console to show changes
xmlDocument.Save(Console.Out);

Note that white space can be an issue when deciding what "up one
position" means.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,252
Latest member
MeredithPl

Latest Threads

Top