views:

145

answers:

2

How do I add another element/childnode to a specific parent node in an XML file?

Specifically a new video object to the media node. I want to turn this:

<?xml version="1.0" encoding="utf-8" ?>
<media>
    <Video name="Gladiator">
     <English>path1</English>
     <Chinese>path2</Cinese>
     <French>path3</French>
    </Video>
    <Video name="Transformers">
     <English>path4</English>
     <Chinese>path5</Cinese>
     <French>path6</French>
    </Video>
</media>

into this:

<?xml version="1.0" encoding="utf-8" ?>
<media>
    <Video name="Gladiator">
     <English>path1</English>
     <Chinese>path2</Cinese>
     <French>path3</French>
    </Video>
    <Video name="Transformers">
     <English>path4</English>
     <Chinese>path5</Cinese>
     <French>path6</French>
    </Video>
    <Video name="Terminator">
     <English>path7</English>
     <Chinese>path8</Cinese>
     <French>path9</French>
    </Video>
</media>

If I open an xmlTextwriter, create a new element tag, add attributes and end the element tag; it deletes all previous data in the text file :/

A: 

I would do something along these lines:

mediaElement.AppendChild(xmlDocument.CreateElement("Video"))

Where mediaElement is a reference to the <media/> element and xmlDocument is of the type XmlDocument.

Chris Missal
think without prerequisites known, the TS doesn't even know why his attempt deletes the data from the file, how should he know how to create the "mediaElement" as reference to the tag. therefore -1
BeowulfOF
+3  A: 

If you use the class XmlTextWriter, you need to read your xml file to get the content before using XmlTextWriter. XmlTextWriter does not load the content of your xml file. That's why all your previous data are gone.

XmlDocument is the simplest way to add a new node.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);

XmlNode node = FindYourNode(xmlDoc); //Method to find the specific node
node.AppendChild(yourNewXmlNode);

xmlDoc.Save(filePath);

If your xml file is small, the class XmlDocument is perfectly fine. But if you have to manipulate a big xml file, I would suggest to use another class because XmlDocument can hurt your performance.

In that case, I would use a combination of XmlReader and XmlWriter.

Francis B.
good explanation, +1
BeowulfOF
Thanx you helped me find the complete answer: http://www.java2s.com/Code/CSharp/XML/AppendChild.htm
see_sharp_guy