日期:2014-05-20  浏览次数:20781 次

Linq - xml 修改問題
以下是我的xml格式

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <item>
  <Name>terst</Name>
  <Model>645</Model>
  </item>
  <item>
  <Name>terst2</Name>
  <Model>6425</Model>
  </item>
</Root>


如何透過linq修改資料 ?

------解决方案--------------------
请详细看看这个帖子,介绍的很详细,LIQN对XML的增删改查基本操作
http://www.cnblogs.com/mingmingruyuedlut/archive/2011/01/27/1946239.html
------解决方案--------------------
http://download.csdn.net/detail/chaichangaini/3718057
------解决方案--------------------
C# code

 string xml = @"<?xml version='1.0' encoding='utf-8'?>
<Root>
  <item>
  <Name>terst</Name>
  <Model>645</Model>
  </item>
  <item>
  <Name>terst2</Name>
  <Model>6425</Model>
  </item>
</Root>

";

            XDocument doc = XDocument.Parse(xml);
            if (doc != null && doc.Root != null)
            {
                Console.WriteLine("root Name:{0}", doc.Root.Name);
                foreach (var item in doc.Root.Nodes())
                {
                    Console.WriteLine("\troot child Name:{0}", ((XElement)item).Name);
                    foreach (var d in ((XElement)item).Nodes())
                    {
                        Console.WriteLine("\t\tName:{0},Value:{1}", ((XElement)d).Name, ((XElement)d).Value);
                    }
                }
            }            
            Console.WriteLine("编辑之后");
            XElement el = new XElement("item1");
            ((XElement)doc.Root.Nodes().Last()).AddAfterSelf(el);
            if (doc != null && doc.Root != null)
            {
                Console.WriteLine("root Name:{0}", doc.Root.Name);
                foreach (var item in doc.Root.Nodes())
                {
                    Console.WriteLine("\troot child Name:{0}", ((XElement)item).Name);
                    foreach (var d in ((XElement)item).Nodes())
                    {
                        Console.WriteLine("\t\tName:{0},Value:{1}", ((XElement)d).Name, ((XElement)d).Value);
                    }
                }
            }     
            //doc.Save("fileName")