- var bench = new XElement("bench",
- new XElement("toolbox",
- new XElement("handtool", "Hammer"),
- new XElement("handtool", "Rasp")
- ),
- new XElement("toolboox",
- new XElement("handtool", "Saw"),
- new XElement("powertool", "Nailgun")
- ),
- new XComment("Be carrful with the nail gun")
- );
- foreach (XNode Node in bench.Nodes())
- {
- Console.WriteLine(Node.ToString(SaveOptions.DisableFormatting) + ".");
- }
- //訪問返回型態為xElement子節點
- foreach (XElement e in bench.Elements())
- {
- Console.WriteLine(e.Name + "=" + e.Value);
- }
- //LINQ 查詢Nailgun
- IEnumerable<string> query =
- from toolbox in bench.Elements()
- where toolbox.Elements().Any(tool => tool.Value == "Nailgun")
- select toolbox.Value;
- foreach (string e in query)
- {
- Console.WriteLine(e);
- }
- //將bench節點值直接設定成test
- bench.SetValue("test");
- Console.WriteLine(bench.ToString());
- //將第一個Node取代為XComment
- XElement items = XElement.Parse("<items><one/><two/><three/></items>");
- items.FirstNode.ReplaceWith(new XComment("One was here"));
- Console.WriteLine(items.ToString(SaveOptions.DisableFormatting));
- #endregion
- #region xml practice
- //CURD XML
- XElement xmls = XElement.Load("../../XML.xml");
- Console.WriteLine(xmls.ToString());
- if (xmls.Element("name") != null)
- {
- xmls.Element("name").Value = "Andy";
- }
- Console.WriteLine(xmls.ToString());
- //移除Andy
- xmls.Elements().Where(e => e.Value == "Andy")
- .Remove();
- Console.WriteLine(xmls.ToString());
- //移除phone
- xmls.Elements().Where(e => e.Name == "phone")
- .Remove();
- Console.WriteLine(xmls.ToString());
2014年4月9日 星期三
[linq] LINQ To XML Part2
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言