XElement config = XElement.Parse ( @""); foreach (XElement child in config.Elements()) child.Name.Dump ("Child element name"); XElement client = config.Element ("client"); bool enabled = (bool) client.Attribute ("enabled"); // Read attribute --client enabled.Dump ("enabled attribute"); client.Attribute ("enabled").SetValue (!enabled); // Update attribute --True int timeout = (int) client.Element ("timeout"); // Read element--30 timeout.Dump ("timeout element"); client.Element ("timeout").SetValue (timeout * 2); // Update element client.Add (new XElement ("retries", 3)); // Add new elememt config.Dump ("Updated DOM"); config.Descendants ("client").Count().Dump ("Count of all clients");//2 config.Elements ("client").Count().Dump("Count of Elements");//2 config.FirstNode.Dump ("FirstNode"); config.FirstNode.AddAnnotation ("Hello FirstNode");//增加注释 config.FirstNode.Annotation 30 90 ().Dump ("String annotations"); config.FirstNode.RemoveAnnotations ();//移除注释 config.FirstNode.Annotation ().Dump ("String annotations"); config.FirstNode.Dump ("Hello FirstNode"); config.LastNode.Dump ("LastNode"); config.FirstNode.AddAfterSelf(new XElement ("client",new XElement ("timeout",120),new XElement ("retries",30))); config.Dump("After calling items.FirstNode.AddAfterSelf"); config.FirstNode.ReplaceWith (new XComment ("client was here")); config.Dump("Notice to change of FirstNode "); config.FirstNode.Remove(); config.Dump("After"); //config.Add(new XElement ("client",new XElement ("timeout", new XText ("12"),new XText ("0")))); config.Add(new XElement ("client",new XAttribute ("id", "IDProperty"),new XElement ("timeout", "12","0"))); config.Dump("After of Add");
StreamingElement
new XStreamingElement ("customers", from c in Customers where c.ID==4 select new XStreamingElement ("customer", new XAttribute ("id", c.ID), new XElement ("name", c.Name), new XElement ("buys", c.Purchases.Count) ) )
Result:
Mary 3
Transforming an X-DOM
void Main() { XElement project = XElement.Parse (@""); XNamespace ns = project.Name.Namespace; IEnumerable AnyCPU 9.0.11209 paths = from compileItem in project.Elements (ns + "ItemGroup").Elements (ns + "Compile") let include = compileItem.Attribute ("Include") where include != null select include.Value; var query = new XElement ("Project", ExpandPaths (paths)); query.Dump(); } static IEnumerable ExpandPaths (IEnumerable paths) { var brokenUp = from path in paths let split = path.Split (new char[] { '\\' }, 2) orderby split[0] select new { name = split[0], remainder = split.ElementAtOrDefault (1) }; IEnumerable files = from b in brokenUp where b.remainder == null select new XElement ("file", b.name); IEnumerable folders = from b in brokenUp where b.remainder != null group b.remainder by b.name into grp select new XElement ("folder", new XAttribute ("name", grp.Key), ExpandPaths (grp) ); return files.Concat (folders); }
result:
ObjectGraph.cs Program.cs AssemblyInfo.cs Aggregation.cs RecursiveXml.cs