4

I have an XML document I'm trying to traverse, which is SDMX-compliant. Here's a short sample:

<root>
    <csf:DataSet id="J10"> 
     <kf:Series> 
       <value> 107.92
       </value> 
     </kf:Series> 
    </csf:DataSet>
</root>

However, when I try to do the following using Linq to Xml in C#, I get an XmlException.

XElement dataset = document.Element("csf:DataSet");

The Exception text is: The ':' character, hexadecimal value 0x3A, cannot be included in a name.

I have no control over the XML. Any ideas on how I can overcome this?

jehuty
  • 528
  • 1
  • 6
  • 20
  • 2
    Note that the ":" is not a special character in a tag. It s separator that separates the namespace prefix from the local name of the element. – John Saunders Nov 26 '10 at 20:53
  • 1
    Your XML is missing namespace declarations. See my full example. If you try to run it without "xmlns:crf=... " the Parse method throws an exception. – m0sa Nov 26 '10 at 21:01
  • @Saunders, @m0sa: Thanks for the heads-up. The full document does have a xmlns entry, I just wasn't aware that the ns was for namespace! Thanks, again. – jehuty Nov 26 '10 at 21:06

3 Answers3

3
var csf = XNamespace.Get("<csfNamespaceUri>");
document.Element(csf + "DataSet");

Note that you have to specify the uri of the csf namespace. A full example:

var doc = XDocument.Parse(@"
<root xmlns:csf=""http://tempuri.org/1"" xmlns:kf=""http://tempuri.org/2"">
    <csf:DataSet id=""J10""> 
     <kf:Series> 
       <value> 107.92
       </value> 
     </kf:Series> 
    </csf:DataSet>
</root>
");

var dataSet = doc.Descendants(XNamespace.Get("http://tempuri.org/1") + "DataSet").Single();
m0sa
  • 10,712
  • 4
  • 44
  • 91
0

I had the same problem. One of the answers here helped me on my way, but not all the way, so here is my solution / clarification:

What you need to do is specify an URL for your namespace, like this:

XNamespace ns = "http://www.example.com";

...then prepend that namespace in each Element:

var someElement = new XElement(ns + "ElementName", "Value");


For this to work however, you must include that specific URI in the XML as follows:

var rootElement = 
    new XElement(ns + "MyRootElement",
                 new XAttribute(XNamespace.Xmlns + "ns", 
                                "http://www.example.com"));

Now you can add someElement (and others) to rootElement, and the namespace will be included, because it has been referenced (by the url) in the root:

rootElement.Add(someElement);
rootElement.Add(new XElement(ns + "OtherElement", "Other value"));

This will generate XML that looks something like this:

<ns:MyRootElement xmlns:ns="http://www.example.com">
    <ns:ElementName> (...) </ns:ElementName>
    <ns:OtherElement> (...) </ns:OtherElement>
</ns:MyRootElement>
Kjartan
  • 18,591
  • 15
  • 71
  • 96
0

Try using XNamespace to qualify the DataSet element you are looking to extract.

MrEyes
  • 13,059
  • 10
  • 48
  • 68