VB Programmer wrote:
I have this xml file...
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<images>
<pic>
<image>http://www.somesite.com/mypic.jpg</image>
<caption>Picture 1 is here</caption>
</pic>
<pic>
<image>http://www.somesite.com/mypic2.jpg</image>
<caption>Picture 2 is here</caption>
</pic>
</images>
Using VB.NET how could I add, edit and remove a <pic> item, consisting of an
<image> and <caption>? Any sample code you could post? I'm an xml newb.
XmlDocument doc = new XmlDocument();
doc.Load(..);
To add a new Item with an attribute and an image-Child node with some
text content use:
XmlElement newItem = doc.CreateElement("pic");
XmlElement newImage = doc.CreateElement("image");
newImage.AppendChild( doc.CreateTextNode("http://...") );
newItem.AppendChild( newImage );
doc.DocumentElement.AppendChild( newItem );
There are many ways to remove an item. Most flexible is to use XPath:
XmlElement e = doc.SelectSingleNode("/images/pic[starts-with(caption,
'Picture 1')]") as XmlElement;
e.ParentNode.RemoveChild( e );
Or you could remove the first pic:
doc.DocumentElement.RemoveChild( doc.DocumentElement.FirstChild );
Editing nodes is mostly just adding and removing their child nodes. Only
Text-Nodes can be directly altered.
Best thing is to see the documentation:
<http://msdn2.microsoft.com/library/System.Xml.XmlDocument>
<http://msdn2.microsoft.com/library/System.Xml.XmlNode>
<http://msdn2.microsoft.com/library/System.Xml.XmlElement>
--
Pascal Schmitt