умножить значения в XML-файле через приложение c # forrm - PullRequest
0 голосов
/ 22 ноября 2018

Я хочу сделать редактор XML для игры на c #.У меня есть готовое приложение ac # forms, но мне нужно выяснить, как умножить значения в выбранном XML-файле.

XML выглядит следующим образом:

<missions>
<mission type="harvest" reward="2862" status="0" success="false">
    <field id="27" sprayFactor="0.000000" spraySet="false" plowFactor="0.000000" state="2" vehicleGroup="3" vehicleUseCost="520.447510" growthState="7" limeFactor="1.000000" weedFactor="1.000000" fruitTypeName="SOYBEAN"/>
    <harvest sellPoint="12" expectedLiters="10539.061523" depositedLiters="0.000000"/>
</mission>
<mission type="harvest" reward="2699" status="0" success="false">
    <field id="4" sprayFactor="0.500000" spraySet="false" plowFactor="0.000000" state="2" vehicleGroup="11" vehicleUseCost="490.897491" growthState="6" limeFactor="1.000000" weedFactor="1.000000" fruitTypeName="COTTON"/>
    <harvest sellPoint="17" expectedLiters="13012.056641" depositedLiters="0.000000"/>
</mission>
<mission type="harvest" reward="8620" status="0" success="false">
    <field id="6" sprayFactor="1.000000" spraySet="false" plowFactor="1.000000" state="2" vehicleGroup="8" vehicleUseCost="1567.417480" growthState="5" limeFactor="1.000000" weedFactor="1.000000" fruitTypeName="SUNFLOWER"/>
    <harvest sellPoint="12" expectedLiters="54337.136719" depositedLiters="0.000000"/>
</mission>
<mission type="transport" reward="307" status="0" success="false" timeLeft="114865506" config="WATER" pickupTrigger="TRANSPORT04" dropoffTrigger="TRANSPORT01" objectFilename="data/objects/pallets/missions/transportPalletBottles.i3d" numObjects="1"/>

Я хочу умножить все значения reward = "xxxxx"

Мой код c # выглядит следующим образомэто:

 public Form1()
    {
        InitializeComponent();
        CenterToScreen();
        string multiply = textBox1.Text;
    }

    XmlDocument missions;
    string path;
    private string lang;

    public void radioButton2_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton2.Checked == true)
        {
            lang = "en";
        }
    }

    public void radioButton1_CheckedChanged(object sender, EventArgs e)
    {
        if (radioButton1.Checked == true)
        {
            lang = "nl";
        }
    }

    public void button2_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string strfilelocation = openFileDialog1.FileName;
            textBox2.Text = strfilelocation;
            path = strfilelocation;
            missions = new XmlDocument();
            missions.Load(path);
        }
    }

    public void button4_Click(object sender, EventArgs e)
    {
        if (lang == "en")
        {
            MessageBox.Show("This tool is developed to make the wages of the contractjobs higher, thus giving you more money when you complete them. Select the desired percentage wich you want the program to multiply the wages with, and select the missions.xml in your desired savegame. Click apply, and then save. You need to run this program every once in a while, to update the wages, or use it once and copy the file. (disclaimer: when you have raised wages, and you run teh program again, and jobs with raised wages are still in missions.xml, the wages will get even higher then is was.)");
        } else if (lang == "nl")
        {
            MessageBox.Show("This tool is developed to make the wages of the contractjobs higher, thus giving you more money when you complete them. Select the desired percentage wich you want the program to multiply the wages with, and select the missions.xml in your desired savegame. Click apply, and then save. You need to run this program every once in a while, to update the wages, or use it once and copy the file. (disclaimer: when you have raised wages, and you run teh program again, and jobs with raised wages are still in missions.xml, the wages will get even higher then is was.)");
        }
        }

Есть ли простой способ сделать это?Если да, может ли кто-нибудь указать мне направление?Я не прошу весь код, просто небольшой запуск, потому что я застрял на этом этапе.

Заранее спасибо!

/////////////////////////////////////////// Новая ошибка;

System.Xml.XmlException: 'Dataна корневом уровне недействителен.Строка 1, позиция 1. '

код:

var text = path;

        var xml = XElement.Parse(text);
        var rewards = xml
                      .Descendants()
                      .Where(d => d.Attribute("reward") != null)
                      .Select(d => d.Attribute("reward"));
        // Do something with rewards. For instance, displaying them in the console
        rewards.ToList().ForEach(r => Console.WriteLine(r.Value));

1 Ответ

0 голосов
/ 22 ноября 2018

Я немного сократил XML, чтобы пропустить текст, который нам не нужен.Код извлекает все награды.Вы можете делать с ними все, что вам нужно:

var text = @"
    <missions>
        <mission type='harvest' reward='2862' status='0' success='false'>
        </mission>
        <mission type='harvest' reward='2699' status='0' success='false'>
        </mission>
        <mission type='harvest' reward='8620' status='0' success='false'>
        </mission>
        <mission type='transport' reward='307' status='0' success='false' />
    </missions>";

var xml = XElement.Parse(text);
var rewards = xml
              .Descendants()
              .Where(d => d.Attribute("reward") != null)
              .Select(d => d.Attribute("reward"));
// Do something with rewards. For instance, displaying them in the console
rewards.ToList().ForEach(r => Console.WriteLine(r.Value));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...