2010-07-20 62 views
2

我试图在我的文件中的特定点插入元素,然后将该文件保存出来。但是,我似乎无法做到。我的XML布局是这样的:在特定标记内插入元素

<?xml version="1.0" encoding="utf-8"?> 
<Settings> 
    <Items /> 
    <Users /> 
</Settings> 

这是我当前的代码:

  XDocument xd = XDocument.Load(@"C:\test.xml"); 

      var newPosition = xdoc.Root.Elements("Users"); 
      //I've tried messing around with newPosition methods 


      XElement newItem = new XElement("User", 
       new XAttribute("Name", "Test Name"), 
       new XAttribute("Age", "34"), 

       ); 

      //how can I insert 'newItem' into the "Users" element tag in the XML file? 

      xd.Save(new StreamWriter(@"C:\test.xml")); 

我想使用LINQ到XML插入“的newitem”入标签。感谢您的帮助。

回答

2

只要找到用户元素,并添加它:

// Note that it's singular - you only want to find one 
XElement newPosition = xdoc.Root.Element("User"); 
XElement newItem = new XElement("User", 
    new XAttribute("Name", "Test Name"), 
    new XAttribute("Age", "34")); 

// Add the new item to the collection of children 
newPosition.Add(newItem); 

您使用的var这里被带坏你 - 因为newPosition在你的代码的类型真的IEnumerable<XElement> ......你都发现User元素。 (好吧,实际上只有一个元素是一个元素,但这是无关的......它仍然是概念上的一个序列。)

+0

嗨,乔恩,这是有道理的。谢谢您的帮助! – Skoder 2010-07-20 18:29:46

相关问题