Can I avoid using fully functional element names in LINQ to XML?

Let's say I call XElement.Parse () with the following line of XML:

var xml = XElement.Parse(@"
  <?xml version="1.0" encoding="UTF-8"?>
  <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <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 request an element, I am forced to use the fully qualified element names because this XML document contains the attribute xmlns

at 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 I really just want

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

      

Is there a way to get LINQ to XML to accept a specific namespace so I don't need to specify it?

+1


a source to share


2 answers


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 adds XNamespace to your string



2) Use VB ?!?

+1


a source


You can simplify by using



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

      

+3


a source







All Articles