简体   繁体   English

无法使用linq to xml c#从xml文档中删除根节点

[英]Unable to remove root node from an xml document using linq to xml c#

Actullay, I need to get all elements except root node from first xml document and so that I could insert them as child nodes to an element(that has same name as a previous doc's root name) in a new document. Actullay,我需要从第一个xml文档中获取除根节点之外的所有元素,以便可以将它们作为子节点插入到新文档中的元素(其名称与先前文档的根名称相同)中。 So I have tried various ways to achieve it, one of them is removing the root node of first and then trying to add elements to a new one's as given below: 因此,我尝试了多种方法来实现它,其中一种是先删除第一个的根节点,然后尝试将元素添加到新的根节点,如下所示:

I have tried the following but could not achieve it. 我尝试了以下方法,但无法实现。

XDocument testDoc = XDocument.Parse(Mydocument);
testDoc.Descendants().Where(e => e.Name.LocalName == "rootName").Select(m=>m).Single().Remove();
var resultDoc = testDoc;

The above code is giving me an empty "{}" result. 上面的代码给了我一个空的“ {}”结果。

my xml document looks something like the below one's: 我的xml文档看起来像下面的样子:

 <rootName xsi:schemaLocation="" xmlns:xsi="" xmlns="">
 <main>
 <child>
 </child>
 <anotherchild>
 </anotherchild>
 </main>
 </rootName>

And another way is getting all the elements of first document as the following: 另一种方法是获取第一个文档的所有元素,如下所示:

  var resultDoc = testDoc.Descendants(ns + "rootName").Elements();

the above statement is giving me the list of elements in the "testDoc" which I need to do something like below, I am clueless: 上面的声明给了我“ testDoc”中的元素列表,我需要做下面的事情,我一无所知:

 <AnotherDocument xsi:schemaLocation="" xmlns:xsi="" xmlns="">
 <firstNode>
 <rootName>

 <main>
 <child>
 </child>
 <anotherchild>
 </anotherchild>
 </main>

 </rootName>
 </firstNode>

Please let me know how to insert those elements in a new document as above if I am correct else let me know the way to resolve this issue. 如果我是正确的,请让我知道如何在上述新文档中插入这些元素,否则请让我知道解决此问题的方法。 Thanks in advance. 提前致谢。

You can replace content of rootName element in another document with elements from first document root: 您可以用第一个文档根目录中的元素替换另一个文档中rootName元素的内容:

var xDoc = XDocument.Parse(Mydocument);
var anotherXDoc = XDocument.Load("anotherdata.xml");
XNamespace ns = "http://..."; // your xml namespance
var rootName = anotherXDoc.Descendants(ns + "rootName").First();
rootName.ReplaceNodes(xDoc.Root.Elements());

By this page_nodes gets all nodes now you can used all node by for each loop 通过此page_nodes获取所有节点,现在您可以为每个循环使用by

 var page_nodes = from p in xdoc.Descendants.Where(e => e.Name.LocalName == "rootName").Select(m=>m).Single().Remove() select p;

foreach (var page_node in page_nodes)
 {
    //Do stuff
 }

Wouldn't removing a root node, remove all its child nodes as well? 是否要删除根节点,也要删除其所有子节点? The result you are getting is to be expected I think. 我认为您得到的结果是可以预期的。 You should probably get all the children of the root and copy them to your new document. 您可能应该获取根的所有子代并将其复制到新文档中。

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

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