从XML复制单个节点 [英] Copying a single node from XML

查看:46
本文介绍了从XML复制单个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它通过删除具有指定id的节点以外的所有节点来修改XML文件。我的代码是:



I have a function in which it modifies an XML file by removing all the node other than the node with specified id. My code is:

public static void myTry()
       {
           string pathname = @"c:\Run\itemsnew.xml";
           var xdoc = XDocument.Load(pathname);
           foreach (var item in xdoc.XPathSelectElements("/items/superitem/item[@id!='2']"))
           {
               item.Remove();
               xdoc.Save(pathname);
               //myTry();
           }

           //xdoc.Save(@"d:\itemsnew.xml");

           Console.ReadLine();
       }







我的问题是这个循环只执行一次。也就是说,如果我有4个id为1,2,3和4的节点,那么我在程序执行后获得的XML是一个带有3个节点的XML,其中包含Id为2,3和4但是我需要带有单个节点的XML,即,id = 2的节点。如果我在我自己内部调用我的函数(就像我在第10行评论),我得到了所需的结果。但我怎么能实现同样的目标呢?我应该如何对循环进行编码,以便该函数在一次调用中删除所有具有id!= 2的节点?




What my problem is this loop is only getting executed once. That is, if i have 4 nodes with id's 1,2,3 and 4, the XML which i get after the program execution is an XML with 3 nodes having Id's 2,3 and 4 but I need the XML with a single node, ie, the node with id=2. If i call my function inside itself (like i have commented here in line 10) i get the desired result. But how else can i achieve the same? How should i code the loop so that the function removes all the nodes with id!=2 in a single call?

推荐答案

正如Canny所说,你不应该保存每个通过循环的时间 - 你这样做的工作太多了。但是导致问题的原因是循环中的删除 - 请参阅 http: //msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx [ ^ ]



如果删除是所有你正在做的,你不需要循环,只需删除:

As Canny said, you should not save each time through your loop--you're doing too much work that way. But what's causing your problem is the Remove inside the loop--see http://msdn.microsoft.com/en-us/library/system.xml.linq.xnode.remove.aspx[^]

If removing is all you're doing, you don't need to loop, just remove:
string pathname = @"d:\itemsnew.xml";
var xdoc = XDocument.Load(pathname);
xdoc.XPathSelectElements("/items/superitem/item[@id!='2']").Remove();
xdoc.Save(pathname);





如果你在循环中做了更多,那么使用ToList将元素枚举转换为列表,作为MS链接描述。



If you are doing more inside the loop, then convert your element enumeration to a list using ToList, as the MS link describes.


这篇关于从XML复制单个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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