Evan
Evan

Reputation: 2635

Updating specific things in an XML file

I am trying to create a tool that updates content in an XML file. My biggest issue is how do I get the program to know where to update what.

Here is an example of the first five lines of XML file.

<?xml version="1.0" encoding="UTF-8"?>
<monster name="Demon" nameDescription="a demon" race="fire" experience="6000" speed="280" manacost="0">
    <health now="8200" max="8200"/>
    <look type="35" corpse="5995"/>
    <targetchange interval="5000" chance="10"/>

Let's say I want to modify the value of experience, how do I go about that? I've looked around this website for already existing instructions, but none relate to something like this.

I am using C# Windows Form.

Upvotes: 0

Views: 72

Answers (2)

JB King
JB King

Reputation: 11910

There are numerous ways you could do this:

  1. Using XMLDocument and other built-in classes in .Net. You could open the file and load the XML into the class and then use XPath to get to the attribute. This would be similar to @lazyberezovsky's answer.

  2. The hack-y solution would be to do the string parsing of the text of the file. Look for the experience=" and note that from that and the next " is the value you want to change. This wouldn't be my first suggestion but I have done this at times when I wanted the quickest hack to change an XML file.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

With Linq to Xml you can:

XDocument xdoc = XDocument.Load(path_to_xml); // load xml file
// query for data you want to update
var experience = xdoc.Root.Attribute("experience");
experience.SetValue(42); // update data
xdoc.Save(path_to_xml); // save updated data

Upvotes: 4

Related Questions