开发者

How to get an XElement with special characters in XML tag

开发者 https://www.devze.com 2023-01-26 22:30 出处:网络
I have an XML document I\'m trying to traverse, which is SDMX-compliant. Here\'s a short sample: <root>

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 datase开发者_Go百科t = 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?


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


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消