【问题标题】:Merge xml nodes of same type in C#在C#中合并相同类型的xml节点
【发布时间】:2013-10-02 07:39:30
【问题描述】:

我有 2 个相同类型的 XML 元素(来自具有相同架构的不同 XML 文档),如下所示:

<Parent>
  <ChildType1>contentA</ChildType1>
  <ChildType2>contentB</ChildType2>
  <ChildType3>contentC</ChildType3>
</Parent>

<Parent>
  <ChildType1>contentD</ChildType1>
  <ChildType3>contentE</ChildType3>
</Parent>

元素类型 ChildType1、ChildType2 和 ChildType3 在 Parent 元素中最多可以有一个实例。

我需要做的是将第二个父节点的内容与第一个父节点合并成一个新节点,如下所示:

<Parent>
  <ChildType1>contentD</ChildType1>
  <ChildType2>contentB</ChildType2>
  <ChildType3>contentE</ChildType3>
</Parent>

【问题讨论】:

  • 您不想将第二个节点复制到第一个节点中,而是想用第二个节点覆盖第一个节点。或者你的样本结果是错误的。
  • 覆盖节点意味着结果将不包含 元素。但我同意,复制也不是最好的术语。

标签: c# xml linq-to-xml xelement


【解决方案1】:

使用 Linq to XML 解析源文档。然后在它们之间创建一个联合并按元素名称分组,并根据您的需要使用组中的第一个/最后一个元素创建一个新文档。

类似这样的:

var doc = XElement.Parse(@"
    <Parent>
        <ChildType1>contentA</ChildType1>
        <ChildType2>contentB</ChildType2>
        <ChildType3>contentC</ChildType3>
    </Parent>
");

 var doc2 = XElement.Parse(@"
    <Parent>
        <ChildType1>contentD</ChildType1>
        <ChildType3>contentE</ChildType3>
    </Parent>
");

var result = 
    from e in doc.Elements().Union(doc2.Elements())
    group e by e.Name into g
    select g.Last();
var merged = new XDocument(
    new XElement("root", result)
);

merged 现在包含

<root>
    <ChildType1>contentD</ChildType1>
    <ChildType2>contentB</ChildType2>
    <ChildType3>contentE</ChildType3>
</root>

【讨论】:

    【解决方案2】:

    如果您将两个初始文档命名为 xd0xd1,那么这对我有用:

    var nodes =
        from xe0 in xd0.Root.Elements()
        join xe1 in xd1.Root.Elements() on xe0.Name equals xe1.Name
        select new { xe0, xe1, };
    
    foreach (var node in nodes)
    {
        node.xe0.Value = node.xe1.Value;
    }
    

    我得到了这个结果:

    <Parent>
      <ChildType1>contentD</ChildType1>
      <ChildType2>contentB</ChildType2>
      <ChildType3>contentE</ChildType3>
    </Parent>
    

    【讨论】:

    • 感谢您的回答,它奏效了,但我发现 Mikael 的回答更清楚了
    • @vicch - 很好,但您的问题确实要求替换第一个 xml 中的节点,而不是创建一个全新的文档。我会认为我在技术上更准确?
    • 你是对的,我编辑了这个问题。希望它更接近我现在想要的。
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多