简体   繁体   中英

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?

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

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>

尝试使用XNamespace来限定要提取的DataSet元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM