当元素/根目录具有命名空间作为属性时,查询XDocument查询不起作用 [英] Query an XDocument Query doesn't work when element/root has Namespace as atribute

查看:69
本文介绍了当元素/根目录具有命名空间作为属性时,查询XDocument查询不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,如果节点包含名称空间/属性,我将无法获得任何结果.这是代码:

The problem is that I can not get any results if the node contains namespace/attribute. This is the code:

Dim xmlFromDisk = XDocument.Load("customers.xml")
Dim ukCustomers = <ukCustomers>
                    <%= From cust In xmlFromDisk...<Customer> _
                    Where cust.<Country>.Value = "UK" _
                    Select cust %>
                  </ukCustomers>

当我具有以下customer.xml时,查询有效:

When I have the following customers.xml the query works:

<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer>
    <CustomerID>ALFKI</CustomerID>
    <CompanyName>Alfreds Futterkiste</CompanyName>
    <Country>UK</Country>
  </Customer>
  </Customers>

当我具有以下customer.xml时,查询将不起作用:

When I have the following customers.xml the query DOES NOT work:

    <?xml version="1.0" encoding="utf-8"?>
<Customers xmlns="http://tempuri.org/">
  <Customer>
    <CustomerID>ALFKI</CustomerID>
    <CompanyName>Alfreds Futterkiste</CompanyName>
    <Country>UK</Country>
  </Customer>
  </Customers>

唯一的区别是,Customers元素中的名称空间xmlns ="http://tempuri.org/".

The only difference is the namespace xmlns="http://tempuri.org/" in the Customers element.

推荐答案

当然,因此您还需要指定名称空间. xmlns="..."指示所有不合格后代元素的默认名称空间.

Sure, so you need to specify the namespace as well. xmlns="..." indicates the default namespace for any unqualified descendant elements.

我不知道您将如何在VB中使用XML文字执行此操作,但是在C#中,您只需编写:

I don't know how you'd do it in an XML literal in VB, but in C# you'd just write:

XNamespace ns = "http://tempuri.org/";
var ukCustomers = doc.Root
                     .Elements(ns + "Customer")
                     .Where(x => (string) x.Element(ns + "Country") == "UK");

这是Reflector所示的等效VB代码,被我稍作改动:

This is the equivalent VB code as shown by Reflector and hacked around a bit by me:

Dim ns As XNamespace = "http://tempuri.org/"
Dim ukCustomers =
   (From x In doc.Root.Elements(DirectCast((ns + "Customer"), XName))
    Where (CStr(x.Element(ns + "Country")) = "UK")
    Select x)

这篇关于当元素/根目录具有命名空间作为属性时,查询XDocument查询不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆