Search code examples
c#findxelement

If: XElement Exists, Else Create new one


My XML File:

<?xml version="1.0" encoding="utf-8"?>
<SimpleKD>
  <player name="Tardis">
    <kills>0</kills>
    <deaths>0</deaths>
    </player>
</SimpleKD>

First off, I need to check if the username "Tardis" exists in the xml .element("player").attribute("name").

If it doesn't, i need to create it with kills and deaths at zero. If it does, I need to read kills and deaths and set them to variables.

I have been using XElement to try and do this.. Thanks!

Code used to write the XML:

public static string username = "Tardis";
public static int kills = 0;
public static int deaths = 0;

........

XElement Players = new XElement(
                      "SimpleKD",
                      new XElement("player",
                          new XAttribute("name", username),
                      new XElement("kills", kills),
                      new XElement("deaths", deaths)));

Solution

  • Assuming you have a Player class:

    private static Player GetPlayer(string name, XElement simpleKD)
    {
        var playerElem = simpleKD.Elements("player")
                                 .SingleOrDefault(p => p.Attribute("name").Value == name);
        if (playerElem == null)
        {
            simpleKD.Add(new XElement("player",
                                      new XAttribute("name", name),
                                      new XElement("kills", 0),
                                      new XElement("deaths", 0)));
            return new Player(name);
        }
    
        return new Player(name,
                          (int)playerElem.Element("kills"),
                          (int)playerElem.Element("deaths"));
    }