C#:两个XML文件的差异 - 仅获取已修改/更新的节点

时间:2017-02-27 20:55:14

标签: c# .net xml xmldiff

我想获得已修改的节点列表(添加节点和更新节点)。

这是我的程序和XML文件(更新前后)

fileBeforeUpdate.xml

<?xml version="1.0"?>
<DESCRIPTION>
    <DISTRIBUE_PAR>
      <NOM>Antoni</NOM>
    </DISTRIBUE_PAR>
    <OBJET>Object Node</OBJET>
    <SUPPORT HREF="#MAIL"/>
    <NUMEROS_CHRONO>
      <CHRONO_1>aqwzsxedc-123456</CHRONO_1>
    </NUMEROS_CHRONO>
    <REFERENCE>reference</REFERENCE>
    <DATE>01/03/1994</DATE>
</DESCRIPTION>

fileAfterUpdate.xml

var sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
    XmlDiff diff = new XmlDiff(XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreNamespaces);
    diff.Compare(@"C:\fileBeforeUpdate", @"C:\fileAfterUpdate", true, xmlWriter);
    diff.Algorithm = XmlDiffAlgorithm.Precise;

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(sb.ToString());
 }

Program.cs的

StringBuilder

这是<xd:node match=\"1\"> <xd:node match=\"1\"> <xd:remove match=\"1\" /> <xd:node match=\"2\"> <xd:change match=\"1\">Antoni</xd:change> </xd:node> </xd:node> <xd:node match=\"3\"> <xd:change match=\"@HREF\">#MAIL</xd:change> </xd:node> <xd:node match=\"5\" /> <xd:add> <DATE>01/03/1994</DATE> </xd:add> </xd:node> 输出:

StringBuilder

为了获取添加的节点列表,它很容易(在<xd:add>中,我有节点var addNodes = doc.GetElementsByTagName("xd:add"); var xmlNodesAdded = new StringBuilder(); foreach (XmlNode node in addNodes) { xmlNodesAdded.Append(node.InnerXml); xmlNodesAdded.AppendLine(); } ,节点添加了值和值。)

StringBuilder

但是,要获取已修改的节点(和属性)列表,它会更难......

我怎样才能做到这一点?
xd:change中,节点actions/math.js未指定已更新的节点...

提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用XmlDiffView获取更改的HTML演示文稿。 (在某些情况下,它无法正确识别更改类型)。

public string GetChangeHtml(string originalXML, string changedXML)
{
    XmlDiffView view = new XmlDiffView();
    var diffgram = Diff(originalXML, changedXML);
    string ret = "";
    using (StringReader legacySr = new StringReader(originalXML), diffGramSr = new StringReader(diffgram.ToString()))
    {
        using (XmlReader legacyReader = XmlReader.Create(legacySr), diffgramReader = XmlReader.Create(diffGramSr))
        {
            using (StringWriter sw = new StringWriter())
            {
                view.Load(legacyReader, diffgramReader);
                view.GetHtml(sw);
                ret = sw.ToString();
            }
        }
    }
    return ret;
}

检查下面问题中的代码: XMLDiff fails to recognize differences correcly?