无法在xml文件中获取root元素的子元素

Qua*_*ntm 4 c# xml linq

我有一个xml文件,结构如下:

<textureatlas xmlns="http://www.w3.org/1999/xhtml" imagepath="someImage.png">
  <subtexture name="1" x="342" y="0" width="173" height="171"></subtexture>
  <subtexture name="2" x="0" y="346" width="169" height="173"></subtexture>
  <subtexture name="3" x="0" y="173" width="169" height="173"></subtexture>
  <subtexture name="4" x="0" y="0" width="169" height="173"></subtexture>
  <subtexture name="5" x="342" y="171" width="169" height="173"></subtexture>
  <subtexture name="6" x="169" y="0" width="173" height="171"></subtexture>
  <subtexture name="7" x="169" y="173" width="173" height="171"></subtexture>
  <subtexture name="8" x="169" y="346" width="173" height="171"></subtexture>
  <subtexture name="9" x="342" y="346" width="173" height="171"></subtexture>
</textureatlas>
Run Code Online (Sandbox Code Playgroud)

我希望迭代遍历每个subtexture元素,使用Linqin C#.但是,我的代码不起作用:

var document = XDocument.Load(pathToXml);
var root = document.Root;

if (root == null)
{
    throw new Exception();
}

var subtextureElements =
    from element in root.Elements("subtexture")
    select element;

foreach (var element in subtextureElements)
{
    Debug.WriteLine("okay");
}
Run Code Online (Sandbox Code Playgroud)

调试器不会打印任何内容.当我添加一个断点时,我发现它subtextureElements是空的.我究竟做错了什么?我搜索了互联网,方法root.Elements("subtextures)也没有用.

Jon*_*eet 5

这个电话

root.Elements("subtexture")
Run Code Online (Sandbox Code Playgroud)

请求subtexture没有命名空间的元素.由于名称空间默认使用该xmlns=...属性,它们实际上位于具有URI的名称空间中http://www.w3.org/1999/xhtml.幸运的LINQ to XML使得它很容易使用的命名空间,使用从隐式转换stringXNamespace,然后+运营商命名空间与元素的名称创建一个组合XName:

XNamespace ns = "http://www.w3.org/1999/xhtml";
var subtextureElements = root.Elements(ns + "subtexture");
Run Code Online (Sandbox Code Playgroud)

(通过这种方式在这里使用查询表达式没有任何好处.我怀疑 XDocument.Root对于加载的文档也永远不会为null XDocument.Load.)