C# 将两个xml文件合并为一个的最快方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/982597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:51:18  来源:igfitidea点击:

What is the fastest way to combine two xml files into one

c#xml

提问by paradisontheitroad

If I have two string of xml1 and xml2 which both represent xml in the same format. What is the fastest way to combine these together? The format is not important, but I just want to know how can I get rid off or ?

如果我有两个 xml1 和 xml2 字符串,它们都以相同的格式表示 xml。将这些组合在一起的最快方法是什么?格式不重要,但我只想知道如何摆脱或?

xml1 :

xml1:

<?xml version="1.0" encoding="utf-8"?>
<AllNodes>
   <NodeA>
      <NodeB>test1</NodeB>
      <NodeB>test2</NodeB>
   </NodeA>
</AllNodes>

xm2 :

xm2 :

<?xml version="1.0" encoding="utf-8"?>
<AllNodes>
   <NodeA>
      <NodeB>test6</NodeB>
      <NodeB>test7</NodeB>
   </NodeA>
   <NodeA>
      <NodeB>test99</NodeB>
      <NodeB>test23</NodeB>
   </NodeA>
</AllNodes>

and have something like this :

并有这样的事情:

<?xml version="1.0" encoding="utf-8"?>
    <AllNodes>
          <NodeA>
              <NodeB>test1</NodeB>
              <NodeB>test2</NodeB>
          </NodeA>
         <NodeA>
              <NodeB>test6</NodeB>
              <NodeB>test7</NodeB>
           </NodeA>
           <NodeA>
              <NodeB>test99</NodeB>
              <NodeB>test23</NodeB>
           </NodeA>
    </AllNodes>

采纳答案by Jose Basilio

The easiest way to do this is using LINQ to XML. You can use either Unionor Concatdepending on your needs.

最简单的方法是使用 LINQ to XML。您可以根据需要使用UnionConcat

var xml1 = XDocument.Load("file1.xml");
var xml2 = XDocument.Load("file2.xml");

//Combine and remove duplicates
var combinedUnique = xml1.Descendants("AllNodes")
                          .Union(xml2.Descendants("AllNodes"));

//Combine and keep duplicates
var combinedWithDups = xml1.Descendants("AllNodes")
                           .Concat(xml2.Descendants("AllNodes"));

回答by Sam Schutte

If I were doing this (using C#), I would create a class that I can deserialize this XML to (you can use xsd.exe to do this), and then loop through all the nodes in the object representing the first piece of XML and "Add" them to the AllNodes property of the object representing the second XML.

如果我这样做(使用 C#),我将创建一个类,我可以将这个 XML 反序列化为(您可以使用 xsd.exe 来执行此操作),然后遍历表示第一段 XML 的对象中的所有节点并将它们“添加”到表示第二个 XML 的对象的 AllNodes 属性。

Then serialize the second class back out the XML, and it should look like your 3rd example.

然后将第二个类序列化回 XML,它应该看起来像您的第三个示例。

回答by Alan Hymanson

You have two basic options:

您有两个基本选项:

  1. Parse the xml, combine the data structures, serialize back to xml.

  2. If you know the structure, use some basic string manipulation to hack it. For example, in the example above you could take the inside of allnodes in the two xml blocks and put them in a single allnodes block and be done.

  1. 解析xml,组合数据结构,序列化回xml。

  2. 如果您知道结构,请使用一些基本的字符串操作来破解它。例如,在上面的示例中,您可以将两个 xml 块中的 allnodes 内部放入一个 allnodes 块中,然后完成。

回答by Tomalak

An XSLT transformation could do it:

XSLT 转换可以做到:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="pXml1" select="''" />
  <xsl:param name="pXml2" select="''" />
  <xsl:param name="pRoot" select="'root'" />

  <xsl:template match="/">
    <xsl:variable name="vXml1" select="document($pXml1)" />
    <xsl:variable name="vXml2" select="document($pXml2)" />

    <xsl:element name="{$pRoot}">
      <xsl:copy-of select="$vXml1/*/*" />
      <xsl:copy-of select="$vXml2/*/*" />
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Pass in the names of the files as parameters, as well as the name of the new root element.

传入文件名作为参数,以及新根元素的名称。

Apply to any XML document, e.g. an empty one.

适用于任何 XML 文档,例如空文档。

回答by VVS

If you can guarantee this format you can combine them by doing string manipulation:

如果您可以保证这种格式,您可以通过进行字符串操作来组合它们:

  • Read the first file, keep everything before "</AllNodes>"
  • Read the second file, remove the part up to "<AllNodes>"
  • Combine those strings.
  • 读取第一个文件,保留“</AllNodes>”之前的所有内容
  • 读取第二个文件,删除“<AllNodes>”之前的部分
  • 组合这些字符串。

This should be the fastest way since no parsing is needed.

这应该是最快的方法,因为不需要解析。

const string RelevantTag = "AllNodes";

string xml1 = File.ReadAllText(xmlFile1);
xml1 = xml1.Substring(0, xml.LastIndexOf("</" + RelevantTag + ">"));

string xml2 = File.ReadAllText(xmlFile2);
xml2 = xml2.Substring(xml.IndexOf("<" + RelevantTag + ">") + "<" + RelevantTag + ">".Length, xml1.Length);

File.WriteAllText(xmlFileCombined, xm1 + xml2);

That said I would always prefer the safe way to the fast way.

也就是说,我总是更喜欢安全的方式而不是快速的方式。

回答by rein

Since you asked for the fastest:

既然你要求最快

If (and only if) the xml structure is always consistent: (this is pseudo code)

如果(且仅当)xml 结构始终一致:(这是伪代码)

string xml1 = //get xml1 somehow
string xml2 = //get xml2 somehow
xml1 = replace(xml1, "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
xml1 = replace(xml1, "<allnodes>", "");
xml1 = replace(xml1, "</allnodes>", "");
xml2 = replace(xml2, "<allnodes>", "<allnodes>\n" + xml1);

It's a giant hack but it's fast. Expect to see it on TheDailyWTF when your colleagues find it.

这是一个巨大的黑客,但速度很快。当您的同事找到它时,期待在 TheDailyWTF 上看到它。

回答by Vasu Balakrishnan

If you want to use the XmlDocument, try this

如果你想使用 XmlDocument,试试这个

 var lNode = lDoc1.ImportNode(lDoc2.DocumentElement.FirstChild, true);
 lDoc1.DocumentElement.AppendChild(lNode);

回答by Heba El-Fadly

var doc= XDocument.Load("file1.xml");
var doc1= XDocument.Load("file2.xml");
doc.Root.Add(doc2.Root.Elements());

回答by Rudy Hinojosa

This is the fastest and cleanest way to merge xml files.

这是合并 xml 文件的最快和最干净的方法。

XElement xFileRoot = XElement.Load(file1.xml);
XElement xFileChild = XElement.Load(file2.xml);
xFileRoot.Add(xFileChild);
xFileRoot.Save(file1.xml);

回答by elhumidio

Best solution to me, based on Jose Basilio answer, slightly modified,

对我来说最好的解决方案,基于 Jose Basilio 的回答,稍作修改,

var combinedUnique = xml1.Descendants()
    .Union(xml2.Descendants());
combinedUnique.First().Save(#fullName)