问题描述
我有两个XML文档.我的目标是用第二个Xml文档的全部内容替换第一个文档中的一个节点.因此,第一个文档-父母看起来像这样:
I have two XML documents.My objective is to replace one of the nodes in the first document with the entire contents of the second Xml documents.So the first document - Parent looks something like this:
<Root>
<AgencyName = "Some Agency"/>
<Originator = "Some other Agency"/>
<Type = "AnonymousType"/>
<Details/>
</Root>
第二个文档-孩子如下:
<Root>
<Details>
<Detail1>
...
</Detail1>
<Detail2>
...
</Detail2>
<Detail3>
...
</Detail3>
</Details>
</Root>
必须用第二个文档的内容替换节点<Details/>
.我正在尝试使用Linq to XML来做到这一点.第一个文档在XDocument类中表示,第二个文档在XElement类中表示. <Detail/>
有几个子属性,我在这里没有列出.
The node <Details/>
has to be replaced with the contents of the second document.I am attempting to use Linq to XML to do this. The first document is represented in an XDocument class and the second one is represented in an XElement class. There are several child attributes for <Detail/>
and I haven't listed them here.
我正在尝试使用此XElement类替换第一个文档中的元素.如果我尝试这样的事情,
I am attempting to replace the element from the first document with this XElement class.If I try something like this,
ParentDoc.Element("Details").ReplaceAll(children);
不太可能起作用. 我应该如何替换?
推荐答案
var doc = XDocument.Load(@"C:\Tools\test.xml");
var doc2 = XDocument.Load(@"C:\Tools\test2.xml");
var children = doc2.Root.Element("Details");
var parentNode = doc.Root.Element("Details");
parentNode.ReplaceWith(children);
顺便说一句,您的xml不正确,因此您将获得异常.
By the way, your xml are not correct, so you'll get exceptions.
我尝试过
<Root>
<AgencyName name= "Some Agency"/>
<Originator name= "Some other Agency"/>
<Type name= "AnonymousType"/>
<Details/>
</Root>
和
<Root>
<Details>
<Detail1>
asdf
</Detail1>
<Detail2>
asde
</Detail2>
<Detail3>
eere
</Detail3>
</Details>
</Root>
得到了
<?xml version="1.0" encoding="utf-8"?>
<Root>
<AgencyName name="Some Agency" />
<Originator name="Some other Agency" />
<Type name="AnonymousType" />
<Details>
<Detail1>
asdf
</Detail1>
<Detail2>
asde
</Detail2>
<Detail3>
eere
</Detail3>
</Details>
</Root>
这篇关于使用LINQ合并XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!