So I'm starting to use XML and I'm trying to use it as a database of sorts. I've managed to save it off and read the whole thing in, but now the problem is that I want to be able to search through, get an item, and make it.

My current XML setup is below.

<?xml version="1.0" encoding="utf-8"?>
<Items>
<Object>
  <Index>10</Index>
  <Damage>4650</Damage>
</Object>
<Object>
   <Index>8</Index>
   <Damage>2940</Damage>
</Object>
<SecondObject>
   <Index>10</Index>
   <HP>0</HP>
   <Name>Some Dude</Name>
</SecondObject>
</Items>

So I'd like to be able to call for a "Object" of a certain index then use those details (both the index and the damage) to make an item.

I've tried a few different things but I wasn't able to get anything to work right. Any ideas?

Dani AI

Generated

As and point out, a DataSet is a perfectly valid route for tabular data and quick binding. For a lighter-weight, more object-oriented approach that maps directly to “make an item” logic, LINQ to XML (XDocument) keeps the code simple and makes selective searches easy. The example below finds an <Object> whose <Index> parses to 10, safely parses fields, and builds a small POCO.

class Item { public int Index { get; set; } public int Damage { get; set; } }

var doc = XDocument.Load("items.xml");

// find first <Object> whose <Index> equals 10
XElement found = doc.Root.Elements("Object")
    .FirstOrDefault(e =>
    {
        int idx;
        return int.TryParse((string)e.Element("Index"), out idx) && idx == 10;
    });

if (found != null)
{
    int dmg;
    int.TryParse((string)found.Element("Damage") ?? "0", out dmg);
    var item = new Item { Index = 10, Damage = dmg };
    // item is ready to be used/instantiated
}

Notes and troubleshooting tips: use doc.Root.Elements() (or Descendants() ) when different element names (e.g. <SecondObject>) might also hold an <Index>. Choose FirstOrDefault when a single match is expected; use Where(...).ToList() to collect multiple matches. Validate element existence and use int.TryParse (as shown) to avoid exceptions from malformed data. For stable, schema-driven XML consider XmlSerializer to deserialize into types; for very large files prefer streaming with XmlReader or move to a real database if queries become frequent and large.

Also consider normalizing the XML (e.g., consistent element name like <Item type="second">) so lookups are unambiguous. This clarifies intent and prevents collisions like the two entries with Index=10 in the original sample.

Recommended Answers

All 2 Replies

You can search for C# XPATH on Google for tons of information on this subject. I am not sure you will find exactly what you are looking for.

There may be a better alternative, or atleast worth your time to look at, and that is to use the existing power built into the DataSet class.

For example, you can create your own XML file based database by creating a DataSet with tables, and columns (the schema). You can load this dataset from a file, and make your changes, then save it back to the file.
Lets say you have a DataSet named Config that has several tables.
When your application starts, it can check to see if you have a file named MyConfig.xml, and if so then load it.

Config.ReadXml("MyConfig.xml");

Now your application has all of the tables for this dataset loaded with data and ready to be used. Later when you want to save your changes back to the file:

Config.AcceptChanges();
Config.WriteXml("MyConfig.xml",XmlWriteMode.WriteSchema);

Now because you have all of your data in the DataSet, you can use the standard (robust) features to search, filter, etc. this data.

foreach(DataRow data in Config.Tables["Items"].Select("Index=10"))
{
      MessageBox.Show( (string)data["Damage"] );
}

Hope this helps,
Jerry

DataSet is has a solution of your problem.

Consider the following code:

DataSet ds = new DataSet();
            // Read XML File
            ds.ReadXml(@"c:\test1\WindowsApplication1\a1.xml");

            // Assign Reference of Object - DataTable
           //   DataTable dt=ds.Tables["Object"];
            dataGridView1.DataSource = ds.Tables["Object"];
                      
            dataGridView2.DataSource = ds.Tables["SecondObject"];
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.