合并具有更改列表的XML文件

编程入门 行业动态 更新时间:2024-10-15 10:17:28
本文介绍了合并具有更改列表的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文件

本文发布于:2023-11-29 12:26:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   列表   XML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!