Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

New to XML DOM,and .NET, Need a good push/kick Please :)

Status
Not open for further replies.

Torx

Programmer
Apr 23, 2003
4
US
Can anyone get me started on a project I'm working on? The Online docs aren't helping me much.

My project is to write a visual basic app that will take any XML file (no XSLT or CSS) find a record, clone the record, change the id attribute and add it to the doc as additional node.

example
.....................................
....
- <car id=&quot;0&quot;>
<col id=&quot;Manufacturor&quot;>Ford</col>
<col id=&quot;color&quot;>Blue</col>
</car>
....
......................................
Needs to become
......................................
....
- <car id=&quot;0&quot;>
<col id=&quot;Manufacturor&quot;>Ford</col>
<col id=&quot;color&quot;>Blue</col>
</car>
- <car id=&quot;1&quot;>
<col id=&quot;Manufacturor&quot;>Ford</col>
<col id=&quot;color&quot;>Blue</col>
</car>
....
......................................

Please, Please, Please, Can someone show me some sample code that could do something like this? I am new to XML and .NET so I don't have much of a frame of reference to work from. I have been working with DOM, XMLNodeElements,XMLAttributes, and XMLNodes but all of the object/element/attribute references are kicking my arse.

I have tried to eat my mouse twice! Please end this newb's suffering :).

Thanks for any and all help :)
 
Well, I use C#, not VB.NET, but the framework stuff will be the same.

First, create a new XmlDocument object, then load your XML string into it. Then find the Car nodes using an XPath query. You then clone the node and alter the id attribute. Lastly you add it back into the document.
Code:
XmlDocument MyDoc = new XmlDocument();
MyDoc.LoadXml(YourXmlStringGoesHere);
XmlNodeList MyNodes = MyDoc.SelectNodes(&quot;//car&quot;);
foreach(XmlNode MyCarNode in MyNodes)
{
   XmlNode MyNewCarNode = MyCarNode.CloneNode(true);
   XmlAttribute IDAttr = MyNewCarNode.Attributes.GetNamedItem(&quot;id&quot;);
   if (IDAttr != null)
   {
      IDAttr.Value = &quot;1&quot;;
   }
   MyCarNode.InsertAfter(MyNewCarNode, MyCarNode);
}

Chip H.
 
Thanks Chip H.! :)

I really appreciate it! Thats a BIG help.

You da man.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top