合并具有更改列表的XML文件 [英] Merging an XML file with a list of changes

查看:53
本文介绍了合并具有更改列表的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个XML文件,它们是我无法控制的另一个应用程序生成的.第一个是设置文件,第二个是应该应用于第一个更改的列表.

I have two XML files that are generated by another application I have no control over. The first is a settings file, and the second is a list of changes that should be applied to the first.

主要设置文件:

<?xml version="1.0"?>
<preset>
  <var id="9" opt="0" val="6666666"/>
  <var id="9" opt="1" val="10000000"/>
  <var id="9" opt="2" val="10000000"/>
  <var id="9" opt="3" val="10000000"/>
  <var id="9" opt="4" val="0"/>
  <var id="10" opt="0" val="4"/>
  <var id="11" opt="0" val="0"/>
  <var id="15" opt="0" val="75"/>
  <var id="22" opt="0" val="0,0,127,516" type="rect(l,t,r,b)"/>
  <var id="23" opt="0" val="27,18,92,66" type="rect(l,t,r,b)"/>
  <var id="24" opt="0" val="320"/>
  ... Skip 300 lines ...
</preset>

这是更改的示例:

<?xml version="1.0"?>
<preset>
  <var id="15" opt="0" val="425"/>
  <var id="22" opt="0" val="0,0,127,776" type="rect(l,t,r,b)"/>
  <var id="26" opt="0" val="147"/>
  <var id="27" opt="0" val="147"/>
  <var id="109" opt="1" val="7"/>
  <var id="126" opt="0" val="6,85,85,59" type="crv(t,m,b,vm)"/>
  <var id="157" opt="0" val="1"/>
  ... Skip 10 lines ...
</preset>

每个变量都有一个ID和该ID适用的优化.基本上,我希望将"id="#""和"opt="#""相同的行替换为更改"文件中的版本.在上面的示例中,id="15" opt="0"的值将从75更改为425.

Each variable has an ID and an Optimization that ID applies to. Basically, I'm looking to replace the lines where the id="#" and opt="#" are the same with the version from the "change" file. In the example above, the value for id="15" opt="0" would change from 75 to 425.

在C#中是否有任何干净的方法?乍一看,使用文本查找并使用查找替换类型的方法逐步完成更改似乎是最干净的方法.将其作为XmlDocument处理的方法似乎需要更多工作.

Would there be any clean way in doing this in C#? At first thought, reading as text and stepping through the changes using a find-replace type of method seems the cleanest. An approach handling this as an XmlDocument seems like much more work.

推荐答案

如果文件很大,效率将非常低,但这是使用XmlDocuments的方法:

This would be terribly inefficient if the files get very big, but this is how you can do it with XmlDocuments:

XmlDocument main = new XmlDocument();
main.Load( "main.xml" );

XmlDocument changes = new XmlDocument();
changes.Load( "changes.xml" );

foreach ( XmlNode mainNode in main.SelectNodes( "preset/var" ) )
{
    string mainId = mainNode.Attributes[ "id" ].Value;
    string mainOpt = mainNode.Attributes[ "opt" ].Value;

    foreach ( XmlNode changeNode in changes.SelectNodes( "preset/var" ) )
    {
        if ( mainId == changeNode.Attributes[ "id" ].Value &&
            mainOpt == changeNode.Attributes[ "opt" ].Value )
        {
            mainNode.Attributes[ "val" ].Value = changeNode.Attributes[ "val" ].Value;
        }
    }
}

// save the updated main document
main.Save( "updated_main.xml" );

这篇关于合并具有更改列表的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆