有时,XML文件中缺少一个或多个XML元素。现在,我正在考虑的一个方法是将XML文件与主XML文件(包含所有元素)进行比较,如果缺少任何元素,则在主文件的XML文件中添加该元素。
我将如何实现这个或任何其他更好的想法?
答案 0 :(得分:1)
我在浏览Microsoft网站时找到的最酷的库之一是XmlDiffPatch库。您可以在http://msdn.microsoft.com/en-us/library/aa302294.aspx找到更多信息,但它基本上允许您比较两个文档,找到所有差异,然后应用这些差异。对于压缩xml文件以通过网络发送非常有用
答案 1 :(得分:0)
using System.Xml;
public class Form1
{
XmlDocument Doc1;
XmlDocument Doc2;
string Doc1Path = "C:\\XmlDoc1.xml";
private void Form1_Load(object sender, System.EventArgs e)
{
Doc1 = new XmlDocument();
Doc2 = new XmlDocument();
Doc1.Load(Doc1Path);
Doc2.Load("C:\\XmlDoc2.xml");
Compare();
Doc1.Save(Doc1Path);
}
public void Compare()
{
foreach (XmlNode ChNode in Doc2.ChildNodes) {
CompareLower(ChNode);
}
}
public void CompareLower(XmlNode NodeName)
{
foreach (XmlNode ChlNode in NodeName.ChildNodes) {
if (ChlNode.Name == "#text") {
continue;
}
string Path = CreatePath(ChlNode);
if (Doc1.SelectNodes(Path).Count == 0) {
XmlNode TempNode = Doc1.ImportNode(ChlNode, true);
Doc1.SelectSingleNode(Path.Substring(0, Path.LastIndexOf("/"))).AppendChild(TempNode);
Doc1.Save(Doc1Path);
}
else {
CompareLower(ChlNode);
Doc1.Save(Doc1Path);
}
}
}
public string CreatePath(XmlNode Node)
{
string Path = "/" + Node.Name;
while (!(Node.ParentNode.Name == "#document")) {
Path = "/" + Node.ParentNode.Name + Path;
Node = Node.ParentNode;
}
Path = "/" + Path;
return Path;
}
}
答案 2 :(得分:0)
在我的示例中,顶级节点为<content>
,因此您只需要替换XML文件中的顶级节点即可。
public static void MergeMissingContentFileNodes(string sourceFile, string destFile)
{
string topLevelNode = "content";
XmlDocument srcXml = new XmlDocument();
srcXml.Load(sourceFile);
XmlDocument destXml = new XmlDocument();
destXml.Load(destFile);
XmlNode srcContentNode = srcXml.SelectSingleNode(topLevelNode);
destXml = LoopThroughAndCreateMissingNodes(destXml, srcContentNode, topLevelNode);
destXml.Save(destFile);
}
public static XmlDocument LoopThroughAndCreateMissingNodes(XmlDocument destXml, XmlNode parentNode, string parentPath)
{
foreach (XmlNode node in parentNode.ChildNodes)
{
//check if node exists and update destXML
if (node.NodeType == XmlNodeType.Element)
{
string currentPath = string.Format("{0}/{1}", parentPath, node.Name);
if (destXml.SelectSingleNode(currentPath) == null)
{
dynamic destParentNode = destXml.SelectSingleNode(parentPath);
destParentNode.AppendChild(destParentNode.OwnerDocument.ImportNode(node, true));
}
LoopThroughAndCreateMissingNodes(destXml, node, currentPath);
}
}
return destXml;
}