Blog Map
[Blog Map] This blog is inactive. New blog: EricWhite.com/blog
Sometimes an XML element contains a large number of attributes, and the values of the attributes may be long. When written to the console, such lines wrap, making it hard to read the XML. In particular, the XML responses from SharePoint web services often contain many attributes for each element. However, you can use appropriate settings for an XmlWriter so that the attributes are aligned, and each attribute is on a separate line. This post shows how to do this.
XNamespace w = "http://www.northwind.com/examples/2008";XElement root = new XElement(w + "Root", new XAttribute(XNamespace.Xmlns + "w", w.NamespaceName), new XAttribute("RootAtt1", 1), new XAttribute("RootAtt2", "This is an attribute with a very long value"), new XAttribute("RootAtt3", 3), new XElement(w + "Child", new XAttribute(w + "Att1", 1), new XAttribute("Att2", 2) ));Console.WriteLine(root);
When this example is run, the console window will look like this:
<w:Root xmlns:w="http://www.northwind.com/examples/2008" RootAtt1="1" RootAtt2="This is an attribute with a very long value" RootAtt3="3"> <w:Child w:Att1="1" Att2="2" /></w:Root>
The following example shows how to use XmlWriter to align attributes:
XNamespace w = "http://www.northwind.com/examples/2008";XElement root = new XElement(w + "Root", new XAttribute(XNamespace.Xmlns + "w", w.NamespaceName), new XAttribute("RootAtt1", 1), new XAttribute("RootAtt2", "This is an attribute with a very long value"), new XAttribute("RootAtt3", 3), new XElement(w + "Child", new XAttribute(w + "Att1", 1), new XAttribute("Att2", 2) ));XmlWriterSettings settings = new XmlWriterSettings();settings.Indent = true;settings.OmitXmlDeclaration = true;settings.NewLineOnAttributes = true;using (XmlWriter xmlWriter = XmlWriter.Create(Console.Out, settings)) root.WriteTo(xmlWriter);
This produces the following output:
This is much easier to read if there are many attributes.
There is an approach using LINQ to XML that provides some of the benefits of a strongly typed document object model. The approach consists of declaring a static class with static, initialized XName and XNamespace fields in the class, and then using those XName and XNamespace objects in the LINQ to XML code that creates and queries XML trees.
This post describes the issues and presents a minimal amount of code that shows how to open an Open XML document from a SharePoint list, modify it, and then save it back to either the same location, or a different one if you desire.
Sometimes you want to work with Open XML documents in memory. This blog post presents a bit of code that shows how to work with in-memory documents as a MemoryStream. The code works with either Open XML SDK V1 or CTP1 of the Open XML SDK V2.
By combining LINQ to SQL with LINQ to Objects in this fashion, you can write some pretty simple C# code that uses LINQ to join data across two separate, disparate data sources.