Replacing XML Elements programmatically with either VB.Net or C#

J

James Fifth

Hello and God Bless,

I am stumped trying to get a simple xml database replacing certain data
with other data programmatically. This is what my xml looks like.

****************************************
<Root_Element>
<Topic index="1">
<Sub_Topic>
<Notes></Notes>
<Notes></Notes>
</Sub_Topic>
</Topic>
<Topic index="2">
<Sub_Topic>
<Notes></Notes>
<Notes></Notes>
<Notes></Notes>
</Sub_Topic>
<Sub_Topic>
<Notes></Notes>
</Sub_Topic>
</Topic>
<Topic index="3">
<Sub_Topic>
<Notes></Notes>
</Sub_Topic>
</Topic>
</Root_Element>
****************************************

What i want to do is navigate to <Topic index="2">, and replace all
child nodes under it with new nodes.

Keep in mind that the number of nodes replacing the current ones will be
different. For instance, i wll replace the 2 <Sub_Topics> under <Topic
index="2"> with 4 <Sub_Topics> with different <Notes> under them.

I can read both C# and VB.Net, so it doesnt matter what language you
write in. Please help me.

Thank you all, and God Bless.
 
S

Saurabh

XmlDocument xdoc = new XmlDocument();
string strXML = "<Root_Element><Topic
index=\"1\"><Sub_Topic><Notes>";
strXML += "</Notes><Notes></Notes></Sub_Topic></Topic>";
strXML += "<Topic index=\"2\"><Sub_Topic><Notes></Notes>";
strXML += "<Notes></Notes><Notes></Notes></Sub_Topic><Sub_Topic>";
strXML += "<Notes></Notes></Sub_Topic></Topic><Topic index=\"3\">";
strXML +=
"<Sub_Topic><Notes></Notes></Sub_Topic></Topic></Root_Element>";
xdoc.LoadXml(strXML);
while(xdoc.HasChildNodes)
{
for(int i = 0; i < xdoc.SelectNodes("/Root_Element/").Count; i++)
{
if(xdoc.GetElementsByTagName("Topic").Attributes[0].Value.ToString().Equals("2"))
{
/* Now Replace the childNodes */
}
}
}
 
S

Saurabh

This code is for retrieval:

XmlDocument xdoc = new XmlDocument();
string strXML = "<Root_Element><Topic
index=\"1\"><Sub_Topic><Notes>";
strXML += "</Notes><Notes></Notes></Sub_Topic></Topic>";
strXML += "<Topic index=\"2\"><Sub_Topic><Notes></Notes>";
strXML += "<Notes></Notes><Notes></Notes></Sub_Topic><Sub_Topic>";
strXML += "<Notes></Notes></Sub_Topic></Topic><Topic index=\"3\">";
strXML +=
"<Sub_Topic><Notes></Notes></Sub_Topic></Topic></Root_Element>";
xdoc.LoadXml(strXML);
while(xdoc.HasChildNodes)
{
for(int i = 0; i < xdoc.SelectNodes("/Root_Element/").Count; i++)
{
if(xdoc.GetElementsByTagName("Topic").Attributes[0].Value.ToString().Equals("2"))
{
/* Now Replace the childNodes */
}
}
}
 

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

Top