我有一个 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
元素,在 C#
中使用 Linq
。但是,我的代码不起作用:
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)
的方法也不起作用。
最佳答案
这个电话
root.Elements("subtexture")
请求没有 namespace 的名为 subtexture
的元素。由于 namespace defaulting 具有 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 的文档永远不会为 null。载入
,要么。)
关于c# - 无法获取 xml 文件中根元素的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50503168/