如何使用此结构中的linq-to-xml检索子节点并将其添加到选定的类别? [英] How do i retrieve and add child node to a selected category using linq-to-xml from this structure?

查看:56
本文介绍了如何使用此结构中的linq-to-xml检索子节点并将其添加到选定的类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据用户选择的类别将联系人添加到联系人。让我们假设用户从组合框中选择朋友,我将如何添加到所选类别。



I'd like to add "Contact" to "Contacts" based on the selected category by the user. Let's assume the user selects "Friends" from the combobox, how will i add to the selected category.

<PhoneContacts>
  <Categories>
    <Category Name="Colleagues">
      <Contacts />
    </Category>
    <Category Name="Friends">
      <Contacts />
    </Category>
  </Categories>
</PhoneContacts>










Fields to be added is this
<Contact>
<fullname>joe</fullname>
<phoneno>123456</phoneno>
<address>stack overflow</address>
</Contact>

推荐答案

第一步是将数据加载到XML中。您可以使用XDocument加载XML文档,也可以像我下面的示例一样动态构建。在内存中使用XML后,可以使用LINQ查询它以查找要添加或删除数据的元素。要添加数据,只需创建XML并将其添加到节点即可。



The first step it load the data into XML. You can load an XML document using XDocument or you can build on the fly like I did the example below. Once you have the XML in memory, you can query it with LINQ to find the element you want to add or remove data to. To add data, you simply create the XML and add it to the node.

XElement phoneContacts =
	new XElement("PhoneContacts",
		new XElement("Categories",
			new XElement("Category", new XAttribute("Name", "Colleagues")),
			new XElement("Category", new XAttribute("Name", "Friends"))));

//Add Collegue Contact
var colleaguesCategory = (from category in phoneContacts.Element("PhoneContacts")
														.Element("Categories")
														.Elements("Category")
						  where category.Attribute("Name").Value == "Colleagues"
						  select category).First();

XElement contact = new XElement("Contact",
	new XElement("fullname", "Joe"),
	new XElement("phoneno", "555-555-5555"),
	new XElement("address", "123 Main St"));

colleaguesCategory.Add(contact);

//Add Friend Contact
var friendsCategory = (from category in phoneContacts.Element("PhoneContacts")
														.Element("Categories")
														.Elements("Category")
					   where category.Attribute("Name").Value == "Friends"
					   select category).First();

contact = new XElement("Contact",
	new XElement("fullname", "Mom"),
	new XElement("phoneno", "666-666-6666"),
	new XElement("address", "123 South St"));

friendsCategory.Add(contact);





我希望这有帮助!



I hope this helps!


而不是

fellowCategory.Add(联系人);

friendsCategory.Add(联系人);



它将是:

colleaguesCategory.Element(Contacts)。添加(联系人);

friendsCategory.Element(Contacts)。添加(联系人);



感谢您的解决方案。
Instead of
colleaguesCategory.Add(contact);
friendsCategory.Add(contact);

It will be:
colleaguesCategory.Element("Contacts").Add(contact);
friendsCategory.Element("Contacts").Add(contact);

Thanks for the solution.


这篇关于如何使用此结构中的linq-to-xml检索子节点并将其添加到选定的类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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