开发者

Deleting whole sections of my XML file

开发者 https://www.devze.com 2022-12-10 07:40 出处:网络
I have a userlist for a program I\'m designing, and all the users are stored to an XML file, like so:

I have a userlist for a program I'm designing, and all the users are stored to an XML file, like so:

<?xml version="1.0"?>
<Users>
  <User ID="1">
    <nickname>Tom</nickname>
    <password>Sams</password>
    <host>ahost@asd.com</host>
    <email>badrandom@as.com</email>
    <isloggedin>true</isloggedin>
    <permission>10</permission>
  </User>
  <User ID="2">
    <nickname>ohai</nickname>
    <password>asdalkdj9u</password>
    <host>meh@meh.com</host>
    <email>my@email</email>
 开发者_Go百科   <isloggedin>false</isloggedin>
    <permission>1</permission>
  </User>
  <User ID="3">
    <nickname>ohai</nickname>
    <password>sercret</password>
    <host>my@host</host>
    <email>my@email</email>
    <isloggedin>false</isloggedin>
    <permission>1</permission>
  </User>
  <User ID="4">
    <nickname>mib_hr6qhr</nickname>
    <password>YXNsa2RhZGxrYXNk</password>
    <host>adb7e51b@webchat.mibbit.com</host>
    <email>alskd@alskd.com</email>
    <isloggedin>true</isloggedin>
    <permission>1</permission>
  </User>
</Users>

Now, based on the users ID number, I need to be able to delete all reference to that user.

So say, I have ID number 3, how can I completely delete userid number 3's existence from the xml file?

I'm looking for code examples, but any help would be greatly appreciated!


One approach using the XML DOM (.NET 1.x and up) would be to just load the file, find user no. 3, and remove that node, and save the file back:

XmlDocument doc = new XmlDocument();
doc.Load("yourXmlFile.xml");

XmlNode userNo3 = doc.SelectSingleNode("//Users/User[@ID='3']");

if(userNo3 != null)
{
   userNo3.ParentNode.RemoveChild(userNo3);
}

doc.Save("YourNewXmlFile.xml");

Marc


Assuming you have the XML loaded in an XDocument:

using System.Linq;
using System.Xml.Linq;

void Delete()
{
    XDocument document = LoadXML();
    document.Elements("Users")
        .Single(e => e.Attribute("ID").Value == "3")
        .Remove();
}

Of course, this assumes that the user you request will always be present in the XML. To be safe, you should use SingelOrDefault() and check for a null value before deleting.


The problem with linq and DOM approach is that there is a round-trip (parsing/serialization) which can be efficient, vtd-xml has something called incremental update, here is an article that explains it... http://www.codeproject.com/KB/XML/xml_processing_future.aspx

VTDGen vg = new VTDGen();
if (vg.parseFile("your.xml", false)){
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    ap.selectXPath("/users/user[@ID='3']");
    XMLModifier xm = new XMLModifier(vn);
    if (ap.evalXPath()!=-1){
       xm.remove();
       xm.output("new.xml");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消