DeletingspecificAttributesinaXMLFile(ASP.NETv2)
I just wrote a small guestbook for my website and decided to use a XML file instead of a Database. I came accross several problems. That's how I solved them.
That's my example xml file:
<?xml version="1.0" encoding="utf-8"?>
<slGuestbook>
<entry name="testy" email="sersmail" location="locylocy" date="31.07.2005 14:45:11">exampletxt</entry>
<entry name="testy" email="testq" location="locylocy" date="31.07.2005 14:44:57">exampletxt</entry>
</slGuestbook>
that's my function:
public static XmlNode GetNode(XmlNode parentNode, string attrName, string attrValue)
{
XmlNode tmpNode = parentNode;
XmlAttribute tmpAttr = null;
while ((tmpAttr == null) &;amp;&;amp; (tmpNode != null))
{
while ((tmpNode != null) &;amp;&;amp; (tmpNode.LocalName != "entry"))
tmpNode = slGuestbook.NextNode(tmpNode);
try
{
tmpAttr = (XmlAttribute)tmpNode.Attributes.GetNamedItem(attrName);
if (tmpAttr.Value == attrValue)
{
return tmpNode;
}
else
{
tmpAttr = null;
tmpNode = slGuestbook.NextNode(tmpNode);
}
}
catch
{
tmpAttr = null;
}
}
return tmpNode;
}
#region Method NextNode()
/// <summary>
/// Method to jump to next node. It&;acute;s irrelevant if next node is a child or parent node.
/// </summary>
/// <param name="actNode">Actual Node.</param>
/// <returns>Next Node if exists, else null (end of XML!).</returns>
public static XmlNode NextNode(XmlNode actNode)
{
if (actNode.HasChildNodes)
{
return actNode.FirstChild;
}
try
{
if (actNode.NextSibling != null)
{
actNode = actNode.NextSibling;
}
else
{
actNode = actNode.ParentNode;
while (actNode.NextSibling == null)
actNode = actNode.ParentNode;
actNode = actNode.NextSibling;
}
}
catch
{
actNode = null;
}
return actNode;
}
#endregion
And that's how I call it:
string path = Server.MapPath(""/xml/guestbook.xml");
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode parentNode = doc.DocumentElement;
XmlNode toDelete = slGuestbook.GetNode(parentNode, "email", "testq");
parentNode.RemoveChild(toDelete);
doc.Save(path);
That's working great for deleting specific guestbook entries. You can implent that call in any type of front-end to be able to delete entries on the fly.
Andreas Kraus
http://www.sunlab.de (2005-5-19:02:36)
| 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。 |