如何用另一个XDocument中的元素替换一个XDocument中的元素? [英] How to replace elements in one XDocument with elements from another XDocument?

查看:73
本文介绍了如何用另一个XDocument中的元素替换一个XDocument中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多数据项的XDocument.

I have an XDocument that contains a number of data items.

我还有另一个XDocument,其中包含非常小的数据项集合.较小文档中的数据项在匹配路径中具有较大文档中的相应元素.

I have another XDocument that contains a very small collection of data items. The data items in the smaller document have corresponding elements in the larger document at matching paths.

我想做的是遍历较小的文档,对于每个元素,我都想更新较大的文档,以便将其对应的值替换为较小的文档.

What I want to do is loop through the smaller document and for each element I find I want to update the larger document so that its corresponding value is replaced with that of the smaller document.

例如,较大的文档:

<Rootelement>
  <Desktop>
    <A>
      <El1 label="original blah" />
    </A>
  </Desktop>
  <Desktop>
    <B>
      <El2 />
    </B>
  </Desktop>
  <Desktop>
    <C>
      <El3 label="I'm the label" tooltip="I'm the tooltip" />
    </C>
  </Desktop>
</Rootelement>

较小的文档:

<Rootelement>
  <Desktop>
    <C>
      <El3 label="The NEW Label" tooltip="The NEW Tooltip" />
    </C>
  </Desktop>
</Rootelement>

我想将元素放在路径Rootelement/Desktop/C/El3处,并将较大文档中相同路径的元素替换为较小文档中的元素,因此较大文档变为:

I want to take the element at the path Rootelement/Desktop/C/El3 and replace the element at the same path in the larger document with the one from the smaller one, so the large document becomes:

<Rootelement>
  <Desktop>
    <A>
      <El1 label="original blah" />
    </A>
  </Desktop>
  <Desktop>
    <B>
      <El2 />
    </B>
  </Desktop>
  <Desktop>
    <C>
      <El3 label="The NEW Label" tooltip="The NEW Tooltip" />
    </C>
  </Desktop>
</Rootelement>

对我来说最好的方法是什么?

What is the best way for me to do this?

推荐答案

var xDocBig = XDocument.Parse(xmlBig);
var xDocSmall = XDocument.Parse(xmlSmall);

var eBig = xDocBig.XPathSelectElement("/Rootelement/Desktop/C");
var eSmall = xDocSmall.XPathSelectElement("/Rootelement/Desktop/C");

eBig.ReplaceWith(eSmall);

var newXml = xDocBig.ToString();

这篇关于如何用另一个XDocument中的元素替换一个XDocument中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆