在我的asp.net网站上,我有一个xml文件
<Image Header="About">
<Imagepath>group.jpg</Imagepath>
<imagetitle>together is fun!</imagetitle>
</Image>
我有一个页面,在该页面中我有一个文本框和文件上传控件。 如何避免将重复的节点插入xml文件?
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);
答案 0 :(得分:0)
尝试使用XPath查看节点是否已存在。像这样:
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);
}