Disclaimer: All postings are provided "AS IS" with no warranties, and confer no rights. This weblog does not represent the thoughts, intentions, plans or strategies of Microsoft. Because a weblog is intended to provide a semi-permanent point-in-time snapshot, you should not consider out of date posts to reflect current thoughts and opinions.
Recently I had to deal with some XML supplied to a development group that wasn't the greatest in structure. For one, there was inconsistent use of namespaces and each repeating element had the namespace duplicated.
The goal was to retrieve from the XML various element values for a business object.
So, using LINQ to XML, there's some pretty neat ways to go about this. The most succinct that I came up with is below - of course it could be tiny bit more succinct in terms of not using locally scoped variable names but it's there for readability
The trick is use of the XNamespace type, which has an implied constructor, then just passing the namespace qualifier on the LINQ statement as a concatenated variable.
12 public void Test2(string xmlContents)
14 XDocument doc = XDocument.Load(new StringReader xmlContents));
15 XNamespace ns0 = "http://mysimpleXml/rootStuff";
16 XNamespace ns1 = "http://mysimpleXml/customer";
18 var query = from c in doc.Elements( ns0 + "myRoot" ).Elements( ns1 + "customer" )
19 select c;
22 foreach (XElement order in query)
24 string firstname = (from c in order.Elements( ns1 + "firstName" ) select c).First().Value;
25 string lastname = (from c in order.Elements( ns1 + "lastName" ) select c).First().Value;
27 Console.WriteLine("firstName: " + firstname);
28 Console.WriteLine("lastName: " + lastname);
The sample XML is below
1 <?xml version="1.0" encoding="utf-8" ?>
2 <myRoot xmlns="http://mysimpleXml/rootStuff">
3 <customer xmlns="http://mysimpleXml/customer">
7 <customer xmlns="http://mysimpleXml/customer">
If youre running Visual Studio 2008 SP1 and you're also a PowerCommands fan you might run into the issue that VS just crashes with no exception box and only the following error in the Application event log:
.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (000007FEF63D203F) (0)
To correct, you need to have an assembly redirection put into the devenv.exe.config file (which .NET will use for configuration information while running in VS..
<dependentAssembly> <assemblyIdentity name="Microsoft.PowerCommands" publicKeyToken="null" culture="neutral"/> <codeBase version="18.104.22.168" href="C:\Program Files (x86)\PowerCommands\Microsoft.PowerCommands.dll"/> </dependentAssembly>
More is posted here:
One this is for sure, there's plenty of materials on getting ramped on the Microsoft stack.
We now have up on the MSDN Ramp Up center tracks for SharePoint...
Check it out: