C# 如何检索特定命名空间中的元素?

C# 如何检索特定命名空间中的元素?,c#,xml,xpath,C#,Xml,Xpath,我用C#。请考虑以下XML: <item> <title>lorem</title> <description>ipsum</description> <media:category>Sports</media:category> <media:title>Combo</media:title> <media:thumbnail url='http://dolor

我用C#。请考虑以下XML:

<item>
  <title>lorem</title>
  <description>ipsum</description>
  <media:category>Sports</media:category>
  <media:title>Combo</media:title>
  <media:thumbnail url='http://dolor/0.jpg' height='100' width='200'/>
  <media:thumbnail url='http://sit/0.jpg' height='300' width='400'/>
</item>

您可以尝试使用此XPath表达式选择特定命名空间中的所有元素:

//*[namespace-uri()='http://uri-address-here']
例如在C#中:

var xml=@”
洛勒姆
乱数假文
体育
联合体
";
var element=XElement.Parse(xml);
var elements=element.XPathSelectElements(“//*[名称空间-uri()=”http://www.foo.org/']");

但我的根标记没有http://www.foo.org/“。我可以选择元素吗?那么它不是有效的XML
XElement.Parse(xml)
media
前缀未声明的情况下引发异常此方式加载编辑:
XDocument.Parse(xmlString).Root
-未引发异常并返回
XElement
xmlns:media=http://some-url“
必须在XML中的某个位置声明(可能在根元素处)。不一定在
元素处。只要名称空间声明存在,它就可以正常工作
//*[namespace-uri()='http://uri-address-here']
var xml = @"<item xmlns:media='http://www.foo.org/'>
  <title>lorem</title>
  <description>ipsum</description>
  <media:category>Sports</media:category>
  <media:title>Combo</media:title>
  <media:thumbnail url='http://dolor/0.jpg' height='100' width='200'/>
  <media:thumbnail url='http://sit/0.jpg' height='300' width='400'/>
</item>";
var element = XElement.Parse(xml);
var elements = element.XPathSelectElements("//*[namespace-uri()='http://www.foo.org/']");