0

在我的 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);
4

1 回答 1

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);
}
于 2013-04-24T13:15:03.410 回答