简体   繁体   English

存在子元素和值时的XElement替换

[英]XElement Replacement when Child Elements and Value Exist

I have some Xml that I am trying to change the name of the XElement on. 我有一些Xml,我想在上面更改XElement的名称。 The XElement contains both child elements and a value similar to this XElement包含子元素和与此类似的值

<parent>
  Hi I am a value <a href="link">link</a>
</parent>

I tried using the method suggested here but i can only copy either the elements or the value. 我尝试使用此处建议的方法但我只能复制元素或值。 Setting the elements first and then the value wipes out the elements. 首先设置元素,然后设置值将擦除元素。

<newparent>
  Hi I am a value link
</newparent>

Copying the value and then elements duplicates the element text 复制值,然后复制元素文本

<newparent>
  Hi I am a value link <a href="link">link</a>
</newparent>

String manipulation of the value itself escapes all of the brackets. 值本身的字符串操作会转义所有方括号。

<newparent>
  Hi I am a value link &lt;a href="link"&gt;link&lt;/a&gt;
</newparent>

Does someone know of a way to achieve the result of copying the value and elements over to the newly created element correctly? 有人知道一种将结果正确复制到新创建的元素上的方法吗?

If I get your question correctly, you want all the child nodes copied to a new parent with a different name. 如果我正确地回答了您的问题,则希望将所有子节点都复制到具有不同名称的新父节点。 If so, use the Nodes() method. 如果是这样,请使用Nodes()方法。

XElement parent = XElement.Parse("<parent>Hi I am a value <a href=\"link\">link</a></parent>");
var newparent = new XElement("newparent", parent.Nodes());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM