[英]How to get an specific node in xml with namespaces?
I'm dealing to access an specific node from a XML Document. 我正在处理从XML文档访问特定节点的问题。 I realized that this one as a base namespace. 我意识到这是一个基本的命名空间。 Here is the example. 这是例子。
I'm interested to get the value of the node d:MediaUrl from all descendents node (entry). 我有兴趣从所有后代节点(条目)获取节点d:MediaUrl的值。 And I haven't accomplished that. 而且我还没有做到。
When I debug the variable iterator 'i', I can see that the XML includes the default namespace again, something like: 当我调试变量迭代器“ i”时,我可以看到XML再次包含默认名称空间,如下所示:
<entry xmlns="http://schemas.microsoft.com.ado/..."
And also I have to include the another namespace called 'd'. 而且我还必须包括另一个名为“ d”的命名空间。
What can I do to access to that particular nodes? 我该怎么做才能访问该特定节点?
This is what I have. 这就是我所拥有的。
var doc = XDocument.Parse(result);
string BASE_NS = "http://www.w3.org/2005/Atom";
string d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var query = from i in doc.Descendants(XName.Get("entry", BASE_NS))
select new Image()
{
Url = i.Element(XName.Get("MediaUrl", BASE_NS)).Value
};
var results = query.ToList();
I would suggest using XNamespace
rather than XName
(personal preference, mainly - as that's how I've always dealt with namespaces in LINQ to XML). 我建议使用XNamespace
而不是XName
(主要是个人喜好,因为这就是我一直在LINQ to XML中处理名称空间的方式)。 To me it's less effort to set up the namespaces in advance and then use Element(NS + "element name") than to use
XName.Get (though using
XName.Get` is perfectly fine if that's what you want to do. 对我来说,预先设置名称空间然后使用Element(NS + "element name") than to use
XName.Get (though using
XName.Get`完全可以做到)要省力。
If you want to get a all the "MediaUrl" elements for each entry, then I'd do something like this: 如果要为每个条目获取所有“ MediaUrl”元素,则可以执行以下操作:
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var query = (from i in doc.Descendants(d + "MediaUrl")
select new Image()
{
Url = i.Value
}).ToList();
If you want to get only one of them, then you need to do something a little different, depending on which one you wanted to get. 如果您只想获得其中之一,则需要做一些不同的事情,具体取决于您想获得哪一个。
For the properties MediaUrl: 对于属性MediaUrl:
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
var query = (from i in doc.Descendants(m + "properties")
select new Image()
{
Url = i.Element(d + "MediaUrl").Value
}).ToList();
For the Thumbnail MediaUrl: 对于缩略图MediaUrl:
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
var query = (from i in doc.Descendants(d + "Thumbnail")
select new Image()
{
Url = i.Element(d + "MediaUrl").Value
}).ToList();
The key here is to use the namespace in conjunction with the element name in order to retrieve it. 此处的关键是将名称空间与元素名称结合使用以便检索它。
var query = from i in doc.Descendants("{full namespace for prefix d}MediaUrl")
select new Image()
{
Url = i.Value
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.