代码之家  ›  专栏  ›  技术社区  ›  SwiftedMind

无法在XML文件中获取根元素的子级

  •  4
  • SwiftedMind  · 技术社区  · 7 年前

    我有一个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>
    

    我想重复一遍 subtexture 元素,使用 Linq 在里面 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");
    }
    

    调试程序不打印任何内容。当我添加一个断点时,我看到了 subtextureElements 是空的。我做错什么了?我搜索了互联网和方法 root.Elements("subtextures) 也不起作用。

    1 回复  |  直到 7 年前
        1
  •  5
  •   Jon Skeet    7 年前

    这个电话

    root.Elements("subtexture")
    

    请求调用的元素 subtexture 没有命名空间。由于 命名空间默认值 xmlns=... 属性,它们实际上位于带有URI的命名空间中 http://www.w3.org/1999/xhtml . 幸运的是,linq-to-xml使用隐式的 string XNamespace ,然后 + 运算符将命名空间与元素名称组合以创建 XName :

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

    (顺便说一下,在这里使用查询表达式没有好处。我 犯罪嫌疑人 XDocument.Root 对于加载了 XDocument.Load ,或者。)