Children of XElement

The immediate child elements of one XElement are accessible by calling the Element() or Elements() functions. Use the overloads with a name to access specific elements, or without to access all child elements. There are also similar methods like Attribute() and Attributes() that you might find useful.

How to print using XDocument

By using XDeclaration. This will add the declaration. But with ToString() you will not get the desired output. You need to use XDocument.Save() with one of his methods. Full sample: var doc = new XDocument( new XDeclaration(“1.0”, “utf-16”, “yes”), new XElement(“blah”, “blih”)); var wr = new StringWriter(); doc.Save(wr); Console.Write(wr.ToString());

How do I do a deep copy of an element in LINQ to XML?

There is no need to reparse. One of the constructors of XElement takes another XElement and makes a deep copy of it: XElement original = new XElement(“original”); XElement deepCopy = new XElement(original); Here are a couple of unit tests to demonstrate: [TestMethod] public void XElementShallowCopyShouldOnlyCopyReference() { XElement original = new XElement(“original”); XElement shallowCopy = original; … Read more

XML file creation using XDocument in C#

LINQ to XML allows this to be much simpler, through three features: You can construct an object without knowing the document it’s part of You can construct an object and provide the children as arguments If an argument is iterable, it will be iterated over So here you can just do: void Main() { List<string> … Read more

XDocument.ToString() drops XML Encoding Tag

Either explicitly write out the declaration, or use a StringWriter and call Save(): using System; using System.IO; using System.Text; using System.Xml.Linq; class Test { static void Main() { string xml = @”<?xml version=’1.0′ encoding=’utf-8′?> <Cooperations> <Cooperation /> </Cooperations>”; XDocument doc = XDocument.Parse(xml); StringBuilder builder = new StringBuilder(); using (TextWriter writer = new StringWriter(builder)) { doc.Save(writer); … Read more

how to use XPath with XDocument?

If you have XDocument it is easier to use LINQ-to-XML: var document = XDocument.Load(fileName); var name = document.Descendants(XName.Get(“Name”, @”http://demo.com/2011/demo-schema”)).First().Value; If you are sure that XPath is the only solution you need: using System.Xml.XPath; var document = XDocument.Load(fileName); var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace(“empty”, “http://demo.com/2011/demo-schema”); var name = document.XPathSelectElement(“/empty:Report/empty:ReportInfo/empty:Name”, namespaceManager).Value;