关于LINQ to XML的一个简单问题

Fre*_*ood 0 .net c# namespaces linq-to-xml

<root xmlns:h="http://www.w3.org/TR/html4/"
      xmlns:f="http://www.w3schools.com/furniture">

<h:table>
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:tr>
</h:table>

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

</root>
Run Code Online (Sandbox Code Playgroud)

我正在尝试练习LinqToXml,但我无法弄清楚我想要什么.我怎么能查询具有h或f命名空间的表元素?这就是我尝试过的.我尝试了不同的但是没有用.

var query = from item in XDocument.Parse(xml).Elements(ns + "table")
            select item;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

这不起作用,因为您缺少root查询中的元素.这可行:

XNamespace ns = "http://www.w3schools.com/furniture";
var query = XDocument.Parse(xml).Element("root").Elements(ns + "table");
Run Code Online (Sandbox Code Playgroud)

现在,如果问题是你想要找到所有 "table"元素而不管命名空间,你需要这样的东西:

var query = XDocument.Parse(xml)
                     .Element("root")
                     .Elements()
                     .Where(element => element.Name.LocalName == "table");
Run Code Online (Sandbox Code Playgroud)

(编辑:如上所述,XDocument.Root如果你愿意,你可以用来获取根元素.重要的是,尝试table直接从文档节点本身获取元素是行不通的.)