Loading...

Reading XML Namespaces and XLinq

Software
Feb 17, 2011
#csharp
Avatar
Author
Matt Kruskamp

I was writing some XLinq the other day, and an annoying thing happened. All of my queries yeilded no results. I started pulling out my hair and crying in a corner when I looked at the schema again and noticed a namespace declaration on the root element. -_-.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfGeoPlaceDistance
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns="http://skats.net/services/literalTypes">
  <GeoPlaceDistance>
    <ToPlace>84142</ToPlace>
    <ToState>UT</ToState>
    <Distance>1</Distance>
  </GeoPlaceDistance>
</ArrayOfGeoPlaceDistance>

For those of you struggling with Xlinq on namespace declarations here is my codes.

// get the xml from a url that I have created
XElement doc = XElement.Load(url);
// grab the namespace declaration
XNamespace na = doc.GetDefaultNamespace();
// append it to all the queries
var elements = from e in doc.Elements(na + "GeoPlaceDistance")
               select e.Element(na + "ToPlace");

There I grabbed all the zip codes that were listed. I hope this helps someone.

Happy Coding.

1 min read
Share this post:

Comments

comments powered by Disqus

Related Articles

All articles
Software Jul 23, 2010

Deserializing XML and Json in C#

I threw together a quick class to serialize and deserialize objects to xml and json in C#. This code shouldn’t be considered production as you can see there is no error checking and correction.

May 18, 2010

Struck

Built a social media command center for the Gatorade brand. It’s an installation piece showing showing real time social media visualizations on large screens.

Oct 10, 2009

Nineteenth Avenue

A software consulting agency created awesome products for agencies and their clients. Besides running the business I worked with C#, WPF, Asp.

The pixel mine

I'm currently the Co-Founder / CTO with an amazing team at Rentler. We build property management software for independant landlords and their renters using a plethora of technologies.

View work
Illustration Illustration
Top