views:

76

answers:

2

Say I call XElement.Parse() with the following XML string:

var xml = XElement.Parse(@"
  <?xml version="1.0" encoding="UTF-8"?>
  <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/"&gt;
    <Owner>
      <ID>7c75442509c41100b6a413b88b523bd6f46554cdbee5b6cbe27bc08cb3f6a865</ID>
      <DisplayName>me</DisplayName>
    </Owner>
    <AccessControlList>
      <Grant>
        <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
      ...
  ");

When it comes time to query the element, I'm forced to use fully-qualified element names because that XML document contains an xmlns attribute in its root. This requires cumbersome creations of XName instances:

var AWS_XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/";
var ownerElement = xml.Element(XName.Get("AccessControlPolicy", AWS_XMLNS)).Element(XName.Get("Owner", AWS_XMLNS));

When what I really want is simply,

var ownerElement = xml.Element("AccessControlPolicy").Element("Owner");

Is there a way to make LINQ to XML assume a specific namespace so I don't have to keep specifying it?

+2  A: 

You could simplify by using

XNamespace ns = "http://s3.amazonaws.com/doc/2006-03-01/";
var ownerElement = xml.Element(ns + "AccessControlPolicy").Element(ns + "Owner");
Ronnie Overby
+1  A: 

I don't think you can (see Jon Skeet's comment), but there are a few tricks you can do.

1) create an extension method that appends the XNamespace to your string

2) Use VB?!?

Richard Morgan