我正在尝试使用xmldiffpatch写入流。
第一种方法是将我的 xml 写入内存流。第二种方法从文件加载 xml,并为要写入的修补文件创建流。第三种方法实际上是比较这两个文件。我总是觉得两个文件是相同的,即使它们不是,所以我知道我错过了一些东西。
任何帮助不胜感激!
public MemoryStream FirstXml()
{
string[] names = { "John", "Mohammed", "Marc", "Tamara", "joy" };
MemoryStream ms = new MemoryStream();
XmlTextWriter xtw= new XmlTextWriter(ms, Encoding.UTF8);
xtw.WriteStartDocument();
xtw.WriteStartElement("root");
foreach (string s in names)
{
xtw.WriteStartElement(s);
xtw.WriteEndElement();
}
xtw.WriteEndElement();
xtw.WriteEndDocument();
return ms;
}
public Stream SecondXml()
{
XmlReader finalFile =XmlReader.Create(@"c:......something.xml");
MemoryStream ms = FirstXml();
XmlReader originalFile = XmlReader.Create(ms);
MemoryStream ms2 = new MemoryStream();
XmlTextWriter dgw = new XmlTextWriter(ms2, Encoding.UTF8);
GenerateDiffGram(originalFile, finalFile, dgw);
return ms2;
}
public void GenerateDiffGram(XmlReader originalFile, XmlReader finalFile,
XmlWriter dgw)
{
XmlDiff xmldiff = new XmlDiff();
bool bIdentical = xmldiff.Compare(originalFile, finalFile, dgw);
dgw.Close();
StreamReader sr = new StreamReader(SecondXml());
string xmlOutput = sr.ReadToEnd();
if(xmlOutput.Contains("</xd:xmldiff>"))
{Console.WriteLine("Xml files are not identical");
Console.Read();}
else
{Console.WriteLine("Xml files are identical");Console.Read();}
}
以下修改版本有效。
static void Main()
{
SecondXml();
}
public static string FirstXml()
{
string[] names = { "John", "Mohammed", "Marc", "Tamara", "joy" };
var sw = new StringWriter();
var xtw = new XmlTextWriter(sw);
xtw.WriteStartDocument();
xtw.WriteStartElement("root");
foreach (string s in names)
{
xtw.WriteStartElement(s);
xtw.WriteEndElement();
}
xtw.WriteEndElement();
xtw.WriteEndDocument();
return sw.ToString();
}
public static void SecondXml()
{
string secondXml = File.ReadAllText(@"t:something.xml");
string firstXml = FirstXml();
Console.WriteLine("Comparing...");
string result = GenerateDiffGram(firstXml, secondXml);
Console.WriteLine(result);
Console.WriteLine();
Console.WriteLine("Finished compare");
Console.Out.Write(firstXml);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(secondXml);
}
public static string GenerateDiffGram(string originalFile, string finalFile)
{
var xmldiff = new XmlDiff();
var r1 = XmlReader.Create(new StringReader(originalFile));
var r2 = XmlReader.Create(new StringReader(finalFile));
var sw = new StringWriter();
var xw = new XmlTextWriter(sw) {Formatting = Formatting.Indented};
bool bIdentical = xmldiff.Compare(r1, r2, xw);
Console.WriteLine();
Console.WriteLine("bIdentical: " + bIdentical);
return sw.ToString();
}
我实际上并不完全确定您的原始代码出了什么问题。 要比较的 XML 在第一个和第二个读取器中都是空字符串。 由于您无论如何都使用内存流作为后备存储,因此如上所述仅使用字符串不会丢失任何内容。