Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 971
jehuty Avatar asked Oct 30 '25 21:10

jehuty


1 Answers

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();
like image 129
m0sa Avatar answered Nov 01 '25 12:11

m0sa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!