使用math编辑XML文件的值

时间:2015-07-27 15:38:07

标签: xml xml-parsing

我有一个XML文档,内容如下:

<CHandlingDataMgr>
    <HandlingData>
        <Item type="CHandlingData">
            <handlingName>AIRTUG</handlingName>
            <fMass value="1400.000000" />
            <fSteeringLock value="30.000000" />
            <SubHandlingData>
                <Item type="NULL" />
                <Item type="NULL" />
                <Item type="NULL" />
            </SubHandlingData>
        </Item>
        <Item type="CHandlingData">
            <handlingName>ADDER</handlingName>
            <fMass value="1800.000000" />
            <fSteeringLock value="42.000000" />
            <SubHandlingData>
                <Item type="CCarHandlingData">
                    <fBackEndPopUpCarImpulseMult value="0.075000" />
                    <fBackEndPopUpBuildingImpulseMult value="0.030000" />
                    <fBackEndPopUpMaxDeltaSpeed value="0.250000" />
                </Item>
                <Item type="NULL" />
                <Item type="NULL" />
            </SubHandlingData>
        </Item>
    </HandlingData>
</<CHandlingDataMgr>

如果我想减少所有&#34; fMass&#34;的价值?标签减少25%并减少所有&#34; fSteeringlock&#34;的值价值50%,我将如何做到这一点?我应该使用哪些工具?

1 个答案:

答案 0 :(得分:0)

尝试C#XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication37
{
    class Program
    {
        const string FILENAME = @"\temp\test.xml";
        static void Main(string[] args)
        {


            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> Items = doc.Descendants("Item").ToList();
            XAttribute value = null;
            foreach (XElement item in Items)
            {
                XElement fMass = item.Element("fMass");
                if (fMass != null)
                {
                    value = item.Element("fMass").Attribute("value");
                    fMass.Value = (0.75 * ((double)value)).ToString();
                }
                XElement fSteeringLock = item.Element("fSteeringLock");
                if (fSteeringLock != null)
                {
                    value = item.Element("fSteeringLock").Attribute("value");
                    fSteeringLock.Value = (0.5 * ((double)value)).ToString();
                }
            }

            doc.Save(FILENAME);


        }
    }
}