0

In my asp.net website I have a xml file

<Image Header="About">
<Imagepath>group.jpg</Imagepath>
<imagetitle>together is fun!</imagetitle>
</Image>

I have a page and in that page I have a textbox and a file upload control. How can I avoid inserting duplicate nodes into the xml file?

string spath = Server.MapPath("~/multipleimage.xml");
XmlDocument doc = new XmlDocument();
doc.Load(spath);

XmlNode Image = doc.CreateNode(XmlNodeType.Element, "Image", null);
XmlAttribute att = doc.CreateAttribute("Header");
att.Value = "AboutPAPCP";
Image.Attributes.Append(att);

XmlNode Imagepath = doc.CreateNode(XmlNodeType.Element, "Imagepath", null);
string imagepath = FleUpdgallery.FileName;
Imagepath.InnerText = imagepath;                    

string filename = Path.GetFileName(FleUpdgallery.FileName);
FleUpdgallery.SaveAs(Server.MapPath("~/uploads/" + filename));
Image.AppendChild(Imagepath);

doc.SelectSingleNode("//RootImage").AppendChild(Image);
doc.Save(spath);
Storm
  • 684
  • 9
  • 20
user2046904
  • 73
  • 1
  • 2
  • 7

1 Answers1

0

Try using XPath to see if the node already exists. Like this:

string spath = Server.MapPath("~/multipleimage.xml");
XmlDocument doc = new XmlDocument();
doc.Load(spath);

//use XPath to search for the node named Image with an attribute Header="AboutPAPCP"
XmlNodeList existingImages = doc.SelecteNodes("*/Image[@Header='AboutPAPCP']");
//if it wasn't found, then it is safe to insert a new node
if (existingImages == null || existingImages.count == 0)
{
    XmlNode Image = doc.CreateNode(XmlNodeType.Element, "Image", null);
    XmlAttribute att = doc.CreateAttribute("Header");
    att.Value = "AboutPAPCP";
    Image.Attributes.Append(att);

    XmlNode Imagepath = doc.CreateNode(XmlNodeType.Element, "Imagepath", null);
    string imagepath = FleUpdgallery.FileName;
    Imagepath.InnerText = imagepath;                    

    string filename = Path.GetFileName(FleUpdgallery.FileName);
    FleUpdgallery.SaveAs(Server.MapPath("~/uploads/" + filename));
    Image.AppendChild(Imagepath);

    doc.SelectSingleNode("//RootImage").AppendChild(Image);
    doc.Save(spath);
}
tgolisch
  • 6,549
  • 3
  • 24
  • 42