Search code examples
c#linq-to-xmlxelementxmlexceptionxname

How to get an XElement with special characters in XML tag


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?


Solution

  • 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();