简体   繁体   English

如何在XML标记中获取带有特殊字符的XElement

[英]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. 我有一个我试图遍历的XML文档,它符合SDMX标准。 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. 但是,当我尝试在C#中使用Linq to Xml执行以下操作时,我得到一个XmlException。

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

The Exception text is: The ':' character, hexadecimal value 0x3A, cannot be included in a name. 异常文本为:':'字符,十六进制值0x3A,不能包含在名称中。

I have no control over the XML. 我无法控制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. 请注意,您必须指定csf命名空间的uri。 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: 您需要做的是为命名空间指定URL,如下所示:

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

...then prepend that namespace in each Element : ...然后在每个Element该命名空间:

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


For this to work however, you must include that specific URI in the XML as follows: 但是,要使其工作,您必须在XML中包含该特定URI ,如下所示:

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: 现在您可以将someElement (和其他)添加到rootElement ,并且将包含命名空间,因为它已在根中引用(通过url):

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

This will generate XML that looks something like this: 这将生成如下所示的XML:

<ns:MyRootElement xmlns:ns="http://www.example.com">
    <ns:ElementName> (...) </ns:ElementName>
    <ns:OtherElement> (...) </ns:OtherElement>
</ns:MyRootElement>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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